So, I'm spawning a few processes and trying to figure out the PID of the process when it gets some data, here's my code:
var mod_child_process = require('child_process');
var mod_events = require('events');
for (var i=0; i<3; ++i)
{
var childProcess;
childProcess = mod_child_process.spawn('HandShake.exe', ['N:192.168.200.250:3001:1', 'Q:TIME']);
childProcess.stdout.on('data', function(data) {
console.log('stdout (' + childProcess.pid + '): ' + data);
});
}
It always returns a single pid
stdout (78748): 18/7/13 15:46:26
stdout (78748): 18/7/13 15:46:26
stdout (78748): 18/7/13 15:46:27
Thanks in advance.
You're running into a scoping issue with the variable childProcess. Variables in JavaScript are function scoped. Because of this, the variable isn't exclusive to the loop.
Simplified example of code acting how you have it:
for (var i = 0; i < 3; ++i) {
var someNumber = i;
setTimeout(function() {
console.log(someNumber);
}, 100);
}
outputs: 2, 2, 2
And the fix:
for (var i = 0; i < 3; ++i) {
(function() {
var someNumber = i;
setTimeout(function() {
console.log(someNumber);
}, 100);
})();
}
You want to wrap your logic in a closure so that the variable childProcess exists with that scope. The above code outputs the expected 0, 1, 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With