Created
July 27, 2022 07:31
-
-
Save ozgurg/fec4d78999b08dd78de8c35a893ed317 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 | |
import debugFactory from "debug"; | |
import dotenv from "dotenv"; | |
import http from "http"; | |
import app from "./../src/app.js"; | |
const debug = debugFactory(process.env.DEBUG); | |
/** | |
* Enable "dotenv" extension. | |
*/ | |
dotenv.config(); | |
/** | |
* Get port from environment and store in Express. | |
*/ | |
const port = normalizePort(process.env.PORT); | |
app.set("port", port); | |
/** | |
* Create an 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 {*} value | |
* @returns {number|string|false} | |
*/ | |
function normalizePort(value) { | |
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 {*} error | |
* @throws {Error} | |
*/ | |
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); | |
case "EADDRINUSE": | |
console.error(`${bind} is already in use`); | |
process.exit(1); | |
default: | |
throw error; | |
} | |
} | |
/** | |
* Event listener for HTTP server "listening" event. | |
*/ | |
function onListening() { | |
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