How can I execute the node.js module as a child of the node.js program?

Here is my problem. I implemented a small script that does some heavy computing, like the node.js. module So, if I type "node myModule.js", it calculates for a second and then returns a value. Now I want to use this module from my main node.JS program. I could just put all the calculations in the "doSomeCalculation" function and then do:

var myModule = require("./myModule"); myModule.doSomeCalculation(); 

But it will block, so it would be bad. I would like to use it in a non-blocking way, for example, for example, DB calls. So I tried using child_process.spawn and exec, for example:

 var spawn = require("child_process").spawn; var ext = spawn("node ./myModule.js", function(err, stdout, stderr) { /* whatevs */ }); ext.on("exit", function() { console.log("calculation over!"); }); 

But of course this will not work. I tried to use an EventEmitter in myModule by emitting "calculateDone" events and trying to add a linked listener to the "ext" variable in the above example. Still not working.

As for the forks, they are not exactly what I am trying to do. Forks will require the input of the code related to the calculation into the main program, forcing, the calculation in the child, while the parent does everything that he does, and then how can I return the result?

So here is my question: can I use a child process to perform a non-blocking calculation when the calculation is placed in a Node file, or is it just not possible? Should I do a heavy calculation in a Python script instead? In both cases, how to pass arguments to a child process - for example, an image?

+44
nonblocking
Nov 14
source share
2 answers

I think you need the child_process.fork () API.

For example, if you have the following two files:

In main.js:

 var cp = require('child_process'); var child = cp.fork('./worker'); child.on('message', function(m) { // Receive results from child process console.log('received: ' + m); }); // Send child process some work child.send('Please up-case this string'); 

In the worker.js file:

 process.on('message', function(m) { // Do work (in this case just up-case the string m = m.toUpperCase(); // Pass results back to parent process process.send(m.toUpperCase(m)); }); 

Then run main (and create a child workflow for the worker.js code ...)

 $ node --version v0.8.3 $ node main.js received: PLEASE UP-CASE THIS STRING 
+103
Nov 14
source share
— -

No matter what you use as a child (Node, Python, whatever), Node doesn't care. Just make sure your script calculation completes after everything is done and the result is written to stdout .

The reason it doesn't work is because you use spawn instead of exec .

+2
Nov 14
source share



All Articles