Search code examples
node.jserror-handlingconnectionnamed-pipes

Node JS detect if named pipe exists


I'm trying to use named pipes in my application. The problem is when I try to connect to the named pipe before the server is running, I get the following error:

events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: connect ENOENT \\?\pipe\\testpipe
    at Object.exports._errnoException (util.js:870:11)
    at exports._exceptionWithHostPort (util.js:893:20)
    at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1062:14)

How can I check if the pipe exists before attempting to connect to it?

Note: Wrapping my connect code in a try-catch doesn't prevent the error.

Here is my code:

var net = require('net');

var addr = '\\\\?\\pipe\\testpipe';
var client = net.createConnection({ path: addr }, function() {
    console.log("Connected");
    client.on('data', function(data) {
        console.log("Recieved: " + data);
    });
    client.on('error', function(){
        console.log(arguments);
    });
}.bind(this));

Solution

  • Using the domain module prevents a fatal error. The following code can be used to safely run the connect code.

    Not what I was hoping for, but the closed solution since there have been no answers.

    var net = require('net');
    var domain = require('domain');
    
    var addr = '\\\\?\\pipe\\testpipe';
    
    var d = domain.create();
    d.on('error', function(err) {
        console.error(err);
    });
    
    d.run(function() {
        var client = net.createConnection({ path: addr }, function() {
            console.log("Connected");
            client.on('data', function(data) {
                console.log("Recieved: " + data);
            });
            client.on('error', function(){
                console.log(arguments);
            });
        }.bind(this));
    });