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

后端 未结 2 355
北荒
北荒 2020-12-02 10:34

Here\'s my problem. I implemented a small script that does some heavy calculation, as a node.js module. So, if I type \"node myModule.js\", it calculates for a second, then

2条回答
  •  隐瞒了意图╮
    2020-12-02 10:54

    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
    

提交回复
热议问题