Reputation: 309
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?
Upvotes: 1
Views: 820
Reputation: 1116
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);
});
Upvotes: 1