import * as cors from 'cors' import * as express from 'express' import * as createError from 'http-errors' import * as os from 'os' import * as path from 'path' import compression = require('compression') export const localIp = Object.values(os.networkInterfaces()).reduce( (r, list) => r.concat( list.reduce( (rr, i) => rr.concat((i.family === 'IPv4' && !i.internal && i.address) || []), [] ) ), [] )[0] /* eslint-disable no-console */ const port = 4002 const app = express() app.disable('x-powered-by') app.use((req, res, next) => { const { url, method } = req next() }) const corsOptions = { origin: '*', credentials: true, optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204 } app.set('port', port) app.use(cors(corsOptions)) app.use(compression()) app.use(express.static(path.join(__dirname, '../../public'))) const TEST = ['live', 'mjpg'] for (const name of TEST) { app.use(function (req, res, next) { console.log(req.path) if ( req.path.startsWith(`/${name}`) || req.path.startsWith(`/${name}/`) || req.path.startsWith(`/${name}.html/`) ) { if (req.path.endsWith('.js')) { console.log('js') res.sendFile(path.join(__dirname, '../../public', `${name}.js`)) return } res.sendFile(path.join(__dirname, '../../public', `${name}.html`)) return } next() }) } app.use(function (req, res, next) { next(createError(404)) }) function onListening() { console.log(`http://localhost:${port}`) console.log(`http://${localIp}:${port}`) } function onError(error) { if (error.syscall !== 'listen') { throw error } const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges') process.exit(1) break case 'EADDRINUSE': console.error(bind + ' is already in use') process.exit(1) break default: throw error } } const server = app.listen(port, onListening) server.on('error', onError)