In nodejs, how do I check if a port is listening or in use

A variation on the following is what I used:

var net = require('net');

var portInUse = function(port, callback) {
    var server = net.createServer(function(socket) {
    socket.write('Echo server\r\n');
    socket.pipe(socket);
    });

    server.on('error', function (e) {
    callback(true);
    });
    server.on('listening', function (e) {
    server.close();
    callback(false);
    });

    server.listen(port, '127.0.0.1');
};

portInUse(5858, function(returnValue) {
    console.log(returnValue);
});

The actual commit which is a little more involved is https://github.com/rocky/trepanjs/commit/f219410d72aba8cd4e91f31fea92a5a09c1d78f8


Use inner http module:

const isPortFree = port =>
  new Promise(resolve => {
    const server = require('http')
      .createServer()
      .listen(port, () => {
        server.close()
        resolve(true)
      })
      .on('error', () => {
        resolve(false)
      })
  })

You should be able to use the node-netstat module to detect ports that are being listened to. Unfortunately, it seems that it only supports Windows and Linux, as is. However, the changes that would be required to have it support OS X do not look to be terribly large. UPDATE: It now supports OS X...er macOS...er whatever they're calling it now.