Reputation: 34396
I'm having trouble trapping events for a child process in node.js. The process runs correctly, and exits when it's done, so all's fine there. Stdout also pipes correctly, so I can see the output fine. Unfortunately none of my event handlers ever fire, which makes it difficult for me to run my callback when the process is done. My code is below:
var child = child_process.spawn('node',
['processor', reportId.toString()],
{ cwd:cwd, stdio:'pipe', env:env });
child.on('data', function(data) {
console.log('Received data...');
console.log(data.toString('utf8'));
});
child.on('message', function(message) {
console.log('Received message...');
console.log(message);
});
child.on('close', function(code) {
console.log('Child process closed');
});
child.on('disconnect', function(code) {
console.log('Child process disconnected');
callback();
});
child.on('exit', function(code) {
console.log('Child exited with code ' + code);
callback();
});
child.stderr.pipe(process.stderr, { end:true });
child.stdout.pipe(process.stdout, { end:true });
I'm sure I'm doing something wrong but none of the documentation seems to offer a clue as to what the problem might be. Any ideas?
I'm running node 0.10.8 on Windows.
Upvotes: 2
Views: 5733
Reputation: 14060
Spawn doesn't have the same ipc channel built in that fork does so the message event won't fire unless you enable it:
var child = child_process.spawn('node', ['processor', reportId.toString()],{
cwd:cwd,
env:env,
stdio:['ipc'] //enable ipc channel
});
The data event should be on the stdout of child instead of the child itself:
child.stdout.on('data', function(data) {
console.log('Received data...');
console.log(data.toString('utf8'));
});
Upvotes: 5