Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/env node
/**
* Module dependencies.
*/
import http from "http";
import debug from "debug";
import { app, sessionMiddleware } from "./App";
import socketio from "socket.io";
import socketEvents from "./SocketEvents";
debug("mjolnir-api:server");
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
const p = parseInt(val, 10);
if (isNaN(p)) {
// named pipe
return val;
}
if (p >= 0) {
// port number
return p;
}
return false;
}
/**
* Get port from environment and store in Express.
*/
const port = normalizePort(process.env.PORT || "3000");
app.set("port", port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Socket.io
*/
var ios = require('socket.io-express-session');
const io = socketio(server);
io.use(ios(sessionMiddleware));
socketEvents(io);
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== "listen") {
throw error;
}
const bind = typeof port === "string"
? `Pipe ${port}`
: `Port ${port}`;
// handle specific listen errors with friendly messages
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;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
const addr = server.address();
const bind = typeof addr === "string"
? `pipe ${addr}`
: `port ${addr.port}`;
debug(`Listening on ${bind}`);
}
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on("error", onError);
server.on("listening", onListening);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment