Search code examples
javascriptnode.jsspawn

Out of order output when running multiple processes with spawn on node.js


I'm using spawn to run multiple processes in node. Here's my code:

var spawn = require('child_process').spawn;

var log_spawn = function (out) {
    process.stdout.write(out);
};

var exec_1 = spawn('command1', ['-args1');
exec_1.stdout.on('data', log_spawn);
exec_1.stderr.on('data', log_spawn);

var exec_2 = spawn('command2', ['-args2');
exec_2.stdout.on('data', log_spawn);
exec_2.stderr.on('data', log_spawn);

It's working ok, but the output is out of order.

For example, if I run the two commands in the standard command line, I get the following output:

output_command1_line1
output_command1_line2
output_command2_line1
output_command2_line2

However, when I use node with spawn, I get the following:

output_command1_line1
output_command2_line1
output_command1_line2
output_command2_line2

What can I do to fix this so I see messages in the same order that I see them on a regular command line?


Solution

  • command2 starts running before command1 finishes, therefore the output of command1 and command2 are interleaved. If you want command2 to start after command1 finishes, you can listen for the exit event on exec_1

    var spawn = require('child_process').spawn;
    
    var log_spawn = function (out) {
        process.stdout.write(out);
    };
    
    var exec_1 = spawn('command1', ['-args1');
    exec_1.stdout.on('data', log_spawn);
    exec_1.stderr.on('data', log_spawn);
    
    exec_1.stderr.on('exit', function(exitcode) {
        var exec_2 = spawn('command2', ['-args2');
        exec_2.stdout.on('data', log_spawn);
        exec_2.stderr.on('data', log_spawn);
    });