With Node.js, we can create a server and listen on a random port:
var server = net.createServer();
server.listen(0, '127.0.0.1');
The first parameter, port 0
, indicates choose a random port, and 127.0.0.1
indicates to listen on localhost only, as documented.
Does Node.js select a port that isn't in use? Do I have to check that myself and retry if Node.js happens to pick a port that is already open and bound to another application? Does it pick any old port, or only userland ports (>1024)?
The OS assigns the port number. See https://github.com/joyent/node/blob/v0.6.11/lib/net.js#L780-783
On OS X, the assignment is sequential, userland and does not check the port to verify it is not in use.
On Ubuntu 11.04, the assignment is random, userland and also does not check if port is in use.
The script below can be used to test on other platforms. To verify the ports are userland, I ran the script 10,000 times via bash piped to grep -c "port: [0-9]{1,3}" with zero matches.
Yes, the port will be an available port. The operating system selects a port that isn't in use rather than Node.js, but from the end-user perspective, that's more-or-less the same thing.
The documentation no doubt had different wording at the time this question was originally posted in 2012, but as of now (January 2019), it is explicit about this: "If port is omitted or is 0, the operating system will assign an arbitrary unused port...".
No, you do not. You should handle errors anyway as any number of things can go wrong. But writing extra code to test for port availability is not something you need to do.
As far as I know, it will always be an unprivileged port.
For operating systems like macOS that assign available ports sequentially, here is code that shows that the operating system will skip a port if it is unavailable.