0

On Node.js version 10+

Say we have a server listening on a path (unix domain sockets):

const server = net.createServer(socket => {

});

const p = path.resolve(process.env.HOME + '/unix.sock');
server.listen(p);

is there a way to determine if some other server is already listening on path p, before running the above code?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

2 Answers2

1

The easy but kind-of dirty way would be to try and use the port, and see if it throws the EADDRINUSE error.

function isPortTaken(port, fn) {

    var net = require('net')

    var tester = net.createServer()
        .once('error', function (err) {
            if (err.code != 'EADDRINUSE')
                fn(true)
        })
        .once('listening', function () {
            tester.once('close', function () {
                    fn(false)
                })
                .close()
        })
        .listen(port)
}

The callback will give a boolean value.

I was going to write this script myself, but then found it somewhere and made small change to it. You can find the original script here: https://gist.github.com/timoxley/1689041

Dushyant Bangal
  • 6,048
  • 8
  • 48
  • 80
1

An alternative to my existing answer would be creating a client and trying to connect to the server. Based on the result, you can identify whether the unix socket is taken or not.

function isPortTaken(port, fn) {

    var net = require('net');

    var client = new net.Socket();
    client.connect(port, function(err) {
        if(err)
            return fn(false)

        client.destroy();
        fn(true);

    });

}

Warning: In case the server triggers some action on a new connection, this will trigger it.

Dushyant Bangal
  • 6,048
  • 8
  • 48
  • 80
  • This opens up possibility of race condition, your other answer with EADDRINUSE is better, and not dirty at all. This is similar to using fs.access before fs.open, see [the last paragraph in the NodeJS API docs](https://nodejs.org/api/fs.html#fspromisesaccesspath-mode). – Yeti Aug 29 '22 at 11:37