1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Great, .once() is not listed in the offical docs, it worked perfectly.
well if once is not listed in official docs, how are supposed to find more functions that are not listed? by trying typing keywords randomly?
once has been in the docs since Node 0.10 so that comment is extremely outdated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.