Created
May 22, 2017 10:16
-
-
Save jmolero/a79843790df172d46f33369d61b30e42 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
/** | |
* Module dependencies. | |
*/ | |
import http from "http"; | |
import debug from "debug"; | |
import { app, session } 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 | |
*/ | |
const sharedsession = require("express-socket.io-session"); | |
const io = socketio(server); | |
io.use(sharedsession(session)); | |
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