65

Can node.js listen on UNIX socket? I did not find any documentation regarding this. I only saw the possibility of listening on a dedicated port.

0

2 Answers 2

87

To listen for incoming connections in node.js you want to use the net.server class.

The standard way of creating an instance of this class is with the net.createServer(...) function. Once you have an instance of this class you use the server.listen(...) function to tell the server where to actually listen.

If the first argument to listen is a number then nodejs will listen on a TCP/IP socket with that port number. However, if the first argument to listen is a string, then the server object will listen on a Unix socket at that path.

var net = require('net');

// This server listens on a Unix socket at /var/run/mysocket
var unixServer = net.createServer(function(client) {
    // Do something with the client connection
});
unixServer.listen('/var/run/mysocket');

// This server listens on TCP/IP port 1234
var tcpServer = net.createServer(function(client) {
    // Do something with the client connection
});
tcpServer.listen(1234);
Sign up to request clarification or add additional context in comments.

7 Comments

Would it be possible to use child process and socket.io to have a client connection that communicates with a server side application using this method? would a new port/path be needed in order to maintain a 1 to 1 client to app relationship?
For those wondering, you can do this with express 4.x too! Because app.listen is basically a helper function, doing app.listen("/var/run/mysocket") is just as valid.
it seems that the socket file remains after the execution exits. Is there a better way for node to auto remove the sock file when it exits?
@ggedde I also have this problem. Putting fs.unlinkSync(socketPath); before the listen() call worked for me.
@ggedde I created a package back in the day to help with adding process exit listeners: npmjs.com/package/catch-exit The relevant source code for attaching listeners is here: github.com/electrovir/catch-exit/blob/master/src/…
|
33

Yes. It's in the documentation.

https://nodejs.org/api/net.html#net_server_listen_path_backlog_callback

1 Comment

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.