Ohhh
Ohhh

Reputation: 435

How do I listen and spawn multiple child process in nodejs

I am trying to execute the same java jar file as a child process in nodejs in a for loop, but how do I listen to multiple child output???

The test.jar file runs in an infinite loop and all it does is increment and print the number.

Below is my code, and it does spawn multiple child process in nodejs, but it only print the pid for the last child, and the content from other childs are all added to the last child.

var exec = require('child_process').exec, child;
var state = "java -jar " + "c://test.jar "
var exec = require('child_process').exec;

for (var i = 0; i < 10; i++) {

    var child = exec(state);

    // Add the child process to the list for tracking
    p_list.push({process:child, content:""});

    // Listen for any response:
    child.stdout.on('data', function (data) {
        console.log(child.pid, data);
        p_list[i].content += data;
    });

    // Listen for any errors:
    child.stderr.on('data', function (data) {
        console.log(child.pid, data);
        p_list[i].content += data;
    }); 

    // Listen if the process closed
    child.on('close', function(exit_code) {
        console.log('Closed before stop: Closing code: ', exit_code);
    });
}

Upvotes: 5

Views: 11939

Answers (2)

Yuri Zarubin
Yuri Zarubin

Reputation: 11677

You need to close over i when dealing with async processes.

for (var i = 0; i < 10; i++) {
    (function(i){
        var child = exec(state);

        // Add the child process to the list for tracking
        p_list.push({process:child, content:""});

        // Listen for any response:
        child.stdout.on('data', function (data) {

            console.log(child.pid, data);
            p_list[i].content += data;
        });

        // Listen for any errors:
        child.stderr.on('data', function (data) {
            console.log(child.pid, data);
            p_list[i].content += data;
        }); 

        // Listen if the process closed
        child.on('close', function(exit_code) {
            console.log('Closed before stop: Closing code: ', exit_code);
        });
    })(i)
}

Upvotes: 9

WakeskaterX
WakeskaterX

Reputation: 1428

You can try checking out the Cluster API for Node.JS. Basically it lets you have a master process that spins up workers, and then each of those workers is it's own process. I think that's what you need here?

Upvotes: 1

Related Questions