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

后端 未结 5 1321
终归单人心
终归单人心 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:16

    NodeJS supports doing this synchronously. Use this:

    const exec = require("child_process").execSync;
    
    var result = exec("python celulas.py");
    
    // convert and show the output.
        console.log(result.toString("utf8");
    

    Remember to convert the buffer into a string. Otherwise you'll just be left with hex code.

    0 讨论(0)
  • 2021-01-01 10:29

    You should use exec-sync

    That allow your script to wait that you exec is done

    really easy to use:

    var execSync = require('exec-sync');
    
    var user = execSync('python celulas.py');
    

    Take a look at: https://www.npmjs.org/package/exec-sync

    0 讨论(0)
  • 2021-01-01 10:30

    You need to remove the listeners exec installs to add to the buffered stdout and stderr, even if you pass no callback it still buffers the output. Node will still exit the child process in the buffer is exceeded in this case.

    var child = require('child_process').exec('python celulas.py');
    child.stdout.removeAllListeners("data");
    child.stderr.removeAllListeners("data");
    child.stdout.pipe(process.stdout);
    child.stderr.pipe(process.stderr);
    
    0 讨论(0)
  • 2021-01-01 10:34

    Use exit event for the child process.

    var child = require('child_process').exec('python celulas.py')
    child.stdout.pipe(process.stdout)
    child.on('exit', function() {
      process.exit()
    })
    

    PS: It's not really a duplicate, since you don't want to use sync code unless you really really need it.

    0 讨论(0)
  • 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!'])
    })
    
    0 讨论(0)
提交回复
热议问题