How do I run a Node.js script from within another Node.js script

后端 未结 3 573
北荒
北荒 2020-12-04 23:25

I have a standalone Node script called compile.js. It is sitting inside the main folder of a small Express app.

Sometimes I will run the compile.j

3条回答
  •  醉梦人生
    2020-12-05 00:01

    Forking a child process may be useful, see http://nodejs.org/api/child_process.html

    From the example at link:

    var cp = require('child_process');
    
    var n = cp.fork(__dirname + '/sub.js');
    
    n.on('message', function(m) {
      console.log('PARENT got message:', m);
    });
    
    n.send({ hello: 'world' });
    

    Now, the child process would go like... also from the example:

    process.on('message', function(m) {
      console.log('CHILD got message:', m);
    });
    
    process.send({ foo: 'bar' });
    

    But to do simple tasks I think that creating a module that extends the events.EventEmitter class will do... http://nodejs.org/api/events.html

提交回复
热议问题