Skip to content

Instantly share code, notes, and snippets.

@wilmoore
Created April 7, 2019 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilmoore/f1082aa42beccfbc5417aced392c999d to your computer and use it in GitHub Desktop.
Save wilmoore/f1082aa42beccfbc5417aced392c999d to your computer and use it in GitHub Desktop.
Simple Node.js HTTP server with clean formatting of http address and port.
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
const format = (address) => {
if (!address || !address.address) {
throw new TypeError('Invalid input.')
}
return (address.family === 'IPv6')
? `[${address.address}]:${address.port}`
: `${address.address}:${address.port}`
}
server.listen(port, hostname, () => {
console.log(`Server running at http://${format(server.address())}/`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment