I'm working on Express 4 and I have moved one heavy task to a child process. Everything is working fine except that the callback in the parent process is somehow executed more than once. That, is causing the error "can't set headers after they are sent" Why is the first thing happening? Parent process:
var cp = require('child_process').fork('./child.js');
cp.send(data);
cp.on('message', function(data){
console.log('status: '+data.status);
return res.status(200).json(data);
});
Forked process:
process.on('message', function(data){
/*process the data*/
process.send({status: 200});
});
Result:
/*first time*/
status: 200
/*second time*/
status: 200
status: 200
/*third time*/
status: 200
status: 200
status: 200
/*random time*/
status: 200
status: 200
status: 200
status: 200
You are creating a new listener every time, which is why the callback is called n+1 times.
Try using .once()
instead of .on()
Since most libraries using events in Node.js inherit from EventEmitter, you will find related documentation on that page.