Node Module Walk-Through: Get Port

January 19, 2016

Node.js Logo

I had a fun idea for a new blog post series. We’ll pick an NPM module and walk through it together! Hopefully learning some cool things along the way.

Today’s module is get-port by the awesome Sindresorhus!

It’s a very simple module that returns an available port on your network.


It’s very easy to install get-port with NPM!

npm install --save get-port


Usage is also very simple. To get and use an available port on your network, simply run:

const getPort = require('get-port');
getPort().then(port => {
    //=> 51402 

The Code

Luckily for us, the entire module is only 20 lines long! Let’s take a look:

'use strict';
var net = require('net');
var Promise = require('pinkie-promise');

module.exports = function () {
  return new Promise(function (resolve, reject) {
    var server = net.createServer();

    server.on('error', reject);

    server.listen(0, function () {
      var port = server.address().port;

      server.close(function () {

Let’s walk through this file one line at a time!

  1. Strict Mode
  2. Require Node’s net package
  3. Require pinkie-promise ( a polyfill for JavaScript Promises )
  4. A blank line ?
  5. An anonymous function this file will export if required
  6. Return a new Promise
  7. Create a new server
  8. A blank line ?
  9. Exit the program if this is the only active server
  10. If the server has any errors, reject the Promise
  11. A blank line ?
  12. Start a new server on port 0 ( this is where the magic happens )
  13. Make a new variable named port with the server’s port as it’s value
  14. A blank line ?
  15. Stop the server
  16. Resolve the Promise and return the port
  17. That’s it!

The Magic

According to the official Node documentation:

A port value of zero will assign a random port.

So, honestly, if all you wanted was to get a random port you could just use Node’s net library but this package wraps that functionality in a Promise so you can pull the port number out easily.

Have a package you’d like to walk-through next week? Leave it in the comments!