Search code examples
javascriptbindchild-process

the behavior of returned function by binding console.log to console in the context of a child process


p = require('child_process').spawn('sleep', ['100']);

//cp.on('exit', ()=>{console.log('exited')});
cp.on('exit', console.log.bind(console,'exited'));

//cp.on('close',()=> {console.log('closed')});
cp.on('close',console.log.bind(console,'closed'));

setTimeout(()=>{cp.kill()}, 500)

when I run the code with node, the output is:

exited null SIGTERM
closed null SIGTERM

I know bind returns a new function with the first argument as its this context and the rest of them as its parameters.

if I replace commented lines with the line below them, there will be no null SIGTERM in the output. why?


Solution

  • When you use bind(), the arguments you supply are inserted before any arguments provided by the caller. When child_process calls the exit and close event handlers, it passes the process's termination reason as the argument. Since console.log() prints all its arguments, this reason it printed after the value that you used in the bind() call.

    It's roughly equivalent to this:

    cp.on('exit', (...args) => console.log('exited', ...args));