Last active
April 7, 2019 22:26
-
-
Save wilmoore/613d088ead61d63208accb59992c1944 to your computer and use it in GitHub Desktop.
Intrinsic Node.js HTTP server taking into consideration IPv6 address (::)
This file contains hidden or 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'); | |
}); | |
server.listen(port, hostname, () => { | |
const address = server.address() | |
// If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise. | |
// https://nodejs.org/api/net.html#net_server_listen_port_host_backlog_callback | |
const host = (address.family === 'IPv6') | |
? `[${address.address}]:${address.port}` | |
: `${address.address}:${address.port}` | |
const url = `http://${host}` | |
console.log(`Server running at ${url}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment