You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js子进程中console.log绑定console后的回调输出差异原因解析

子进程事件回调:bind写法与箭头函数的输出差异

测试代码

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)

运行输出

exited null SIGTERM
closed null SIGTERM

问题

已知bind方法会返回一个新函数,将第一个参数作为this上下文,其余参数作为预设参数。为何将注释的箭头函数回调替换为下方的bind写法时,输出会多出null SIGTERM,而箭头函数版本则没有该内容?

解答

Node.js 里子进程的exit和close事件触发时,会自动给回调函数传递两个关键参数:

  • 进程退出码code:当进程被信号终止时,这个值为null
  • 终止信号signal:这里就是触发终止的SIGTERM

箭头函数写法的逻辑

箭头函数()=>{console.log('exited')}没有声明接收任何参数,所以调用console.log时只传入了我们指定的字符串'exited',自然不会输出额外内容。

bind写法的逻辑

console.log.bind(console,'exited')只是给console.log预设了第一个参数为'exited',但并没有阻止 Node.js 传递事件自带的参数。当事件触发执行这个绑定后的函数时,事件的code和signal会被追加到预设参数后面传入,相当于最终执行的是console.log('exited', null, 'SIGTERM'),所以会打出null SIGTERM这部分额外内容。

内容的提问来源于stack exchange,提问作者yousef

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 20:50:29