1

I'm having trouble getting my Node.js Unix socket stood up. The Node.js code spawns a C app that acts as the server. The server might not be ready by the time I start trying to connect to it from the Node.js code, so I get an error. I even try to naively catch it, but it doesn't work. Here's a simplified version of the code:

var net = require('net');

const URI_SOCK = '/opt/tmp/.socket';

try {
  const socket = net.connect(URI_SOCK, function() {
    //'connect' listener
    console.log('Connected to socket!');
    socket.write("42");
  });
} catch(err) {
  console.log("Caught you!");
}

Here's what happens when I try to run it:

 ✘ ⚡ ⚙ root@ncooprider-tron  ~  node test.js

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: connect ECONNREFUSED
    at errnoException (net.js:901:11)
    at Object.afterConnect [as oncomplete] (net.js:892:19)

Any ideas for how to catch that error or what to do so I can force the program to wait until the server is ready to receive clients?

1
  • You can loop trying to connect for some period of time (before giving up, if the server couldn't start for some reason) Commented May 5, 2017 at 1:33

1 Answer 1

1

This has been answered a few times before, but you basically need to listen to the "error" event the client emits. Something like:

socket.on('error', function(err) {
  console.log("Error: " + err);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Doh! In my non-example code I do have this event listener, but inside it I try another connect call. That faulty logic needs reworking. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.