Skip to Content
Node Cookbook - Third Edition
book

Node Cookbook - Third Edition

by Matteo Collina, David Mark Clements, Peter Elger, Mathias Buus Madsen
July 2017
Intermediate to advanced
656 pages
16h 1m
English
Packt Publishing
Content preview from Node Cookbook - Third Edition

Binding to a random free port

To assign the server to a random free port, we simply set the port number to 0.

Let's copy the rest-server folder and call the new folder rest-server-random-port.

Now in the rest-server-random-port/index.js file, let's change our port reference near the top of the file to the following:

const port = process.env.PORT || 0 

Next we'll change our server.listen statement at the bottom of the file like so:

server.listen(port, host, () => console.log(JSON.stringify(server.address()))) 

We've added a third callback argument to server.listen. The server binding process is asynchronous, so we won't know which port we're bound to immediately. The callback is triggered once the server has bound to a port, then we can use ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Node Cookbook - Fourth Edition

Node Cookbook - Fourth Edition

Bethany Griggs
Your First Week With Node.js, 2nd Edition

Your First Week With Node.js, 2nd Edition

James Hibbard, Craig Buckler, Mark Brown, Nilson Jacques, James Kolce, Paul Orac, M. David Green, Florian Rappl

Publisher Resources

ISBN: 9781785880087Supplemental Content