UNPKG

camstreamerlib

Version:

Helper library for CamStreamer ACAP applications.

95 lines (94 loc) 3.83 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HttpServer = void 0; const http = require("http"); const url = require("url"); const fs = require("fs"); const path = require("path"); const EventEmitter = require("events"); class HttpServer extends EventEmitter { constructor(options) { var _a, _b, _c, _d; super(); this.host = (_b = (_a = options === null || options === void 0 ? void 0 : options.host) !== null && _a !== void 0 ? _a : process.env.HTTP_HOST) !== null && _b !== void 0 ? _b : '0.0.0.0'; this.port = (_c = options === null || options === void 0 ? void 0 : options.port) !== null && _c !== void 0 ? _c : parseInt((_d = process.env.HTTP_PORT) !== null && _d !== void 0 ? _d : '80'); this.registeredPaths = new Map(); this.server = http.createServer((req, res) => { var _a, _b; this.emit('access', req.method + ' ' + req.url); const parsedUrl = url.parse((_a = req.url) !== null && _a !== void 0 ? _a : ''); (_b = parsedUrl.pathname) !== null && _b !== void 0 ? _b : (parsedUrl.pathname = ''); const requestCallback = this.registeredPaths.get(parsedUrl.pathname); if (requestCallback) { requestCallback(req, res); return; } let pathname = `./html${parsedUrl.pathname}`; const ext = path.parse(pathname).ext; const map = { '.ico': 'image/x-icon', '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.doc': 'application/msword', }; fs.access(pathname, fs.constants.R_OK, (err) => { if (err) { res.statusCode = 404; res.end(`File ${pathname} not found!`); this.emit('error', `File ${pathname} not found!`); return; } if (fs.statSync(pathname).isDirectory()) { pathname += `/index${ext}`; } fs.readFile(pathname, (err, data) => { var _a; if (err) { res.statusCode = 500; res.end(`Error getting the file: ${err}`); this.emit('error', `Error getting the file: ${err}`); } else { res.setHeader('Content-type', (_a = map[ext]) !== null && _a !== void 0 ? _a : 'text/plain'); res.setHeader('Access-Control-Allow-Origin', '*'); res.end(data); } }); }); }); this.server.on('error', (err) => { this.emit('error', err); }); this.server.listen(this.port, this.host); this.sockets = {}; let idTracker = 0; this.server.on('connection', (socket) => { const socketID = idTracker++; this.sockets[socketID] = socket; socket.on('close', () => { delete this.sockets[socketID]; }); }); } getServer() { return this.server; } onRequest(path, callback) { this.registeredPaths.set(path, callback); } close() { this.server.close(); for (const key in this.sockets) { this.sockets[key].destroy(); } } } exports.HttpServer = HttpServer;