Created
April 7, 2019 22:17
-
-
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.
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
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