Skip to content

Instantly share code, notes, and snippets.

@badsyntax
Last active November 28, 2020 21:47
Show Gist options
  • Save badsyntax/708e50315e1621c68544dae354af5afe to your computer and use it in GitHub Desktop.
Save badsyntax/708e50315e1621c68544dae354af5afe to your computer and use it in GitHub Desktop.
Super simple Node.js IPC with Unix domain sockets
const net = require('net');
const socketPath = '/tmp/my.unix.sock';
const server = net
.createServer()
.on('connection', (stream) => {
console.log('Server: client connected');
stream.setEncoding('utf-8');
stream.on('end', () => {
console.log('Server: client disconnected');
});
stream.on('data', (msg) => {
console.log('Server: got client message:', msg);
if (msg === 'command') {
stream.write('command response');
}
});
})
.on('close', () => {
console.log('Server: shut down');
})
.listen(socketPath, () => {
console.log('Server bound to socket at path:', socketPath);
});
const client = net.createConnection(socketPath);
client
.setEncoding('utf-8')
.on('connect', () => {
console.log('Client: connected to server');
client.write('command');
client.end();
server.close();
})
.on('data', (data) => {
console.log('Client: got server message:', data);
})
.on('end', () => {
console.log('Client: disconnected');
})
.on('error', (data) => console.error(data));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment