UNPKG

js-smp-peer

Version:

<p align="center"> <a href="https://github.com/mhchia/js-smp-peer/actions?workflow=nodejs-test"><img alt="GitHub Actions status" src="https://github.com/mhchia/js-smp-peer/workflows/nodejs-test/badge.svg"></a> </p>

74 lines (73 loc) 2.47 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var config_1 = require("./config"); var fs = require("fs"); var express = require("express"); var http = require("http"); var https = require("https"); // NOTE: Using `require` instead of `import` since something is wrong in the types of peer server // "node_modules/peer/index.d.ts:8:43 - error TS2709: " // "Cannot use namespace 'EventEmitter' as a type." var expressPeerServer = require('peer').ExpressPeerServer; var certDir = __dirname + "/../certs"; var keyPath = certDir + "/privkey.pem"; var certPath = certDir + "/cert.pem"; var errCodeFileNotFound = 'ENOENT'; /** * Run a peer server. `runServer` first try to load SSL a pair of cert and key from `certDir`. * If it succeeds, the peer server runs with SSL. Otherwise, without SSL. */ function runServer() { var isSSLSupported; var key; var cert; try { key = fs.readFileSync(keyPath); cert = fs.readFileSync(certPath); isSSLSupported = true; } catch (err) { if (err.code === errCodeFileNotFound) { console.log("Couldn't find certs. Running without SSL..."); isSSLSupported = false; } else { throw err; } } var app = express(); var server; if (isSSLSupported) { server = https.createServer({ key: key, cert: cert }, app); } else { server = http.createServer(app); } var peerServer; if (isSSLSupported) { // Sanity check if (key === undefined || cert === undefined) { throw new Error('key or cert is undefined, but we should have it loaded'); } peerServer = expressPeerServer(server, { ssl: { key: key.toString('utf8'), cert: cert.toString('utf8') }, }); } else { peerServer = expressPeerServer(server); } // TODO: Confirm this is correct app.use(config_1.defaultPeerServerConfig.path, peerServer); // FIXME: Remove it later when we don't need debugging app.use('/', express.static('./demo/')); server.listen(config_1.defaultPeerServerConfig.port); peerServer.on('connection', function (id) { console.log("A client connected : " + id); }); peerServer.on('disconnect', function (id) { console.log("A client say ~ bye bye : " + id); }); // TODO: Listen to more events console.log('PeerServer is ready!'); } runServer();