How to wait for a child process to finish in Node.js?

后端 未结 5 1322
终归单人心
终归单人心 2021-01-01 10:15

I\'m running a Python script through a child process in Node.js, like this:

require(\'child_process\').exec(\'python celulas.py\', function (error, stdout, s         


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-01 10:39

    In my opinion, the best way to handle this is by implementing an event emitter. When the first spawn finishes, emit an event that indicates that it is complete.

    const { spawn } = require('child_process');
    const events = require('events');
    const myEmitter = new events.EventEmitter();
    
    
    firstSpawn = spawn('echo', ['hello']);
    firstSpawn.on('exit'), (exitCode) => {
        if (parseInt(code) !== 0) {
            //Handle non-zero exit
        }
        myEmitter.emit('firstSpawn-finished');
    }
    
    myEmitter.on('firstSpawn-finished', () => {
        secondSpawn = spawn('echo', ['BYE!'])
    })
    

提交回复
热议问题