Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I listen and spawn multiple child process in nodejs

Tags:

node.js

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);
    });
}
like image 984
Ohhh Avatar asked Jan 08 '23 15:01

Ohhh


2 Answers

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)
}
like image 61
Yuri Zarubin Avatar answered Mar 28 '23 02:03

Yuri Zarubin


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?

like image 28
WakeskaterX Avatar answered Mar 28 '23 03:03

WakeskaterX