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

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

require('child_process').exec('python', function (error, stdout, stderr) {

but Node doesn't wait for it to finish. How can I wait for the process to finish?

EDIT: Is it possible to do this by running the child process in a module I call from the main script?


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');

Take a look at:

Use exit event for the child process.

var child = require('child_process').exec('python')
child.on('exit', function() {

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

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');

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.on('firstSpawn-finished', () => {
    secondSpawn = spawn('echo', ['BYE!'])

NodeJS supports doing this synchronously. Use this:

const exec = require("child_process").execSync;

var result = exec("python");

// convert and show the output.

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

Need Your Help

Failed to Open Stream using laravel install

php laravel laravel-5

I am trying out Laravel and after installation I get the following when attempting to start a new application:

Convert Array of Strings to Comma Separated String with additional concatenation

c# string linq concatenation comma

Is there any way to convert a list of strings to a comma-separated string?