Search code examples
node.jsserverport

What happens if I pass server.listen() a string for a port?


See this answer for context: basically, what if I accidentally set process.env.PORT to the string "8080" instead of the string 8080, before calling server.listen(process.env.PORT, ...)?

Does server.listen() perform any type conversion on its arguments?

What is the meaning of

server.address()  // '"8080"'

?

What is the server "listening" to if I pass it a string like server.listen('fake')? Inspecting server.address() in server.listen()'s callback shows 'fake'


Solution

  • Yes, a string is acceptable.

    server.address() tells you the address your server is bound to (this is inherited from the net module).

    If you pass a string that can't be coerced into a number that is in a valid port range, this is an error depending on how many arguments you passed to .listen. The reason for this is that a string could be an IPC path. See the normalization function.