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

…衆ロ難τιáo~ 提交于 2019-11-27 11:06:30

I think what you're after is 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 worker.js:

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 to run main (and spawn a child worker process for the worker.js code ...)

$ node --version
v0.8.3

$ node main.js 
received: PLEASE UP-CASE THIS STRING

It doesn't matter what you will use as a child (Node, Python, whatever), Node doesn't care. Just make sure, that your calculcation script exits after everything is done and result is written to stdout.

Reason why it's not working is that you're using spawn instead of exec.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!