Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

process.send is conditionally defined in Node.js

Tags:

node.js

For whatever reason, in Node.js, the function process.send is defined in some environments but not defined in others. For instance, when I fork a child process from a parent process in Node.js like so:

//parent process
var cp = require('child_process');
var k = cp.fork('./child.js',['arg1','arg2','arg3']);
k.send('fail'); //k.send is defined...
process.send("ok, let's try this..."); //process.send is NOT defined

inside the child process:

//child.js
process.send('message');  //process.send is defined, and will send a message to the parent process above

why is process.send conditionally defined in some Node.js processes but not others? Seems like a poor design decision by Node.js architects.

The only way I know how to get around this is:

if (typeof process.send === 'function') { 
    process.send('what I want to send');
}
like image 866
Alexander Mills Avatar asked Jun 02 '15 00:06

Alexander Mills


People also ask

What is process send?

The process. send() method is an inbuilt application programming interface of the process module which is used by the child process to communicate with the parent process.

What is send in NodeJS?

send(req, path, [options]) Create a new SendStream for the given path to send to a res . The req is the Node. js HTTP request and the path is a urlencoded path to send (urlencoded, not the actual file-system path).

What is Node JS process model?

Node. js runs in a single process and the application code runs in a single thread and thereby needs less resources than other platforms. All the user requests to your web application will be handled by a single thread and all the I/O work or long running job is performed asynchronously for a particular request.


1 Answers

Child processes have a process.send method to communicate back with the process that spawned them, while the root process doesn't have any "parent" to communicate, so its not there. From the docs:

In the child the process object will have a send() method, and process will emit objects each time it receives a message on its channel.

To avoid having to "litter the code with conditionals", a temporary solution might be to just put a "noop" function in its place at the top of any "root" files you might be spawning processes from:

process.send = process.send || function () {};
like image 102
Alex McMillan Avatar answered Sep 22 '22 08:09

Alex McMillan