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

如何在ts-node中优雅处理SIGINT(Ctrl+C)关闭流程?

Twitch机器人SIGINT优雅关闭在ts-node下的异常问题

问题背景

我正在为Twitch机器人实现通过Ctrl+C触发SIGINT信号的优雅关闭功能,使用的是一个基于事件的Twitch聊天模板。

实现的SIGINT处理器

我定义了如下的process.on('SIGINT')处理器:

process.on( 'SIGINT', () => {
    console.log("\nGracefully shutting down from SIGINT (Ctrl-C)");
    fs.writeFile('./commands.json', JSON.stringify(commands, null, 2), (error) => {
        if (error) {
            console.log(`error encountered when saving commands.json: ${error}`)
            process.exit()
        }
        console.log('commands.json successfully written')
        process.exit();
    })
})

不同运行环境的表现

  • Node.js运行.js文件:一切正常
node ./chat_bot.js
...
Gracefully shutting down from SIGINT (Ctrl-C)
commands.json successfully written
PS C:\ProjectDir>
  • ts-node运行.ts文件:程序会在完成文件写入前终止,且出现Terminate batch job (Y/N)?提示,无论选Y/N或再次按Ctrl+C都无法正常完成写入,但确实进入了处理器
npx ts-node --esm ./chat_bot.ts
...
Gracefully shutting down from SIGINT (Ctrl-C)
Terminate batch job (Y/N)?
y // 选n或再次按ctrl-c表现相同
PS C:\ProjectDir>

排查情况

  • 已确认.ts和.js文件中的处理器代码完全一致
  • 使用writeFileSync替代writeFile也会出现相同问题
  • 找到一个ts-node的已关闭问题,声称在v4.0.0中解决,但内容无帮助

配置及版本信息

tsconfig.json配置:

{
    "compilerOptions": {
        "module":"node16",
        "allowImportingTsExtensions": true,
        "noEmit": true,
    },
    
}

版本信息:

  • ts-node v10.9.1
  • typescript v5.0.4
  • node v19.4.0

补充信息

编写最小可复现示例后发现,仅当从单独文件导入ChatBot类时才会出现该问题。推测可能与ts-node未能正确将信号转发给子进程有关,此前在GitHub上看到过相关问题但均已关闭。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 06:05:03