Last active
May 3, 2022 09:59
-
-
Save ozgurg/052679fff88215e28df00419a8855a1b to your computer and use it in GitHub Desktop.
Node + Express bin/www with TypeScript
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 | |
import debugFactory from "debug"; | |
import http from "http"; | |
import app from "./../app"; | |
const debug = debugFactory(process.env.DEBUG); | |
/** | |
* Get port from environment and store in Express | |
*/ | |
const port = normalizePort(process.env.PORT); | |
app.set("port", port); | |
/** | |
* Create a HTTP server | |
*/ | |
const server = http.createServer(app); | |
/** | |
* Listen on provided port, on all network interfaces | |
*/ | |
server.listen(port); | |
server.on("error", onError); | |
server.on("listening", onListening); | |
/** | |
* Normalize a port into a number, string or false | |
* | |
* @param {any} value | |
* @return {number|string|false} | |
*/ | |
function normalizePort(value: any): number|string|false { | |
const port = parseInt(value, 10); | |
// Named pipe | |
if (isNaN(port)) { | |
return value; | |
} | |
// Port number | |
if (port >= 0) { | |
return port; | |
} | |
return false; | |
} | |
/** | |
* Event listener for HTTP server "error" event | |
* | |
* @param {any} error | |
*/ | |
function onError(error: any): void { | |
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); | |
case "EADDRINUSE": | |
console.error(`${bind} is already in use`); | |
process.exit(1); | |
default: | |
throw error; | |
} | |
} | |
/** | |
* Event listener for HTTP server "listening" event | |
*/ | |
function onListening(): void { | |
const address = server.address(); | |
const bind = typeof address === "string" ? `pipe ${address}` : `port ${address.port}`; | |
debug(`Listening on ${bind}`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment