Prasoon Birla
Prasoon Birla

Reputation: 33

IPC using shared memory communication between two unrelated node js processes

I've two unrelated node js processes running on the same windows machine. I want these two processes to communicate with each other but without using FileIO (performance issue) and Sockets(security issue). Is there any way we can do that? I've read about Shared Memory and pipe based communication but could not find any implementation for node js.

Upvotes: 2

Views: 3150

Answers (1)

Luis Perez
Luis Perez

Reputation: 28130

The answer to this depends on whether one node process is launching the other or not. If one node process is launching the other by using fork() then it can communicate using process.send() and process.on('message', ...).

See https://nodejs.org/api/child_process.html#child_process_subprocess_send_message_sendhandle_options_callback

// parent.js
const cp = require('child_process');
const n = cp.fork(`${__dirname}/sub.js`);

n.on('message', (m) => {
  console.log('PARENT got message:', m);
});

// Causes the child to print: CHILD got message: { hello: 'world' }
n.send({ hello: 'world' });

And for the child process:

// child.js

process.on('message', (m) => {
  console.log('CHILD got message:', m);
});

// Causes the parent to print: PARENT got message: { foo: 'bar', baz: null }
process.send({ foo: 'bar', baz: NaN });

If on the other hand the processes are launched separately that's a different story.

This first leads to the question what do you mean when you say that you don't want to use sockets for security reasons?

Are you concerned that your node process would be accessible from outside your computer. Because that would only happen if you bind to ip address 0.0.0.0, or one of your public ip addresses. It shouldn't happen if you bind to 127.0.0.1, then it should only be accessible from your computer.

Traffic going to 127.0.0.1 also bypasses the network so it never leaves your computer or goes to your network card.

Also you can use local named sockets which are even less accessible.

If your concern that some other local service would be able to communicate to your channel, you can get around that by passing secret information or encrypting the content.

You can find more details on using named sockets and pipes in the following Stack Overflow answer: How to create a named pipe in node.js?

Upvotes: 1

Related Questions