← 中文资源

简体中文版本

exit 钩子在进程退出前冲刷数据

process.on('exit') 只在进程自然退出前同步执行一次,适合把未落盘的缓冲冲刷完;在里面启动的异步任务永远等不到完成。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

app work finished, waiting for the loop to drain
exit hook: flushing 3 entries
flushed: login:u1
flushed: order:42
flushed: logout:u1
exit hook done, code 0
no async work possible inside exit hooks

实现说明

循环只出现在 for (const entry of pendingWrites),它的每次迭代处理一个元素。await 标出每个异步边界——没有 fire-and-forget。 各个操作都建立在顶层绑定之上:pendingWrites。

使用要点

  • 直接运行文件,输出会带上标签,比如 no async work possible inside exit hooks、app work finished, waiting for the loop to drain——输出的每一行都能指回产生它的那次调用。

常见问题

有需要管理的依赖吗?

没有。无需声明或安装任何依赖。 文件用顶层绑定保存自己的状态:pendingWrites。

核心语句

process.on('exit', (code) => {
  console.log(`exit hook: flushing ${pendingWrites.length} entries`);
  for (const entry of pendingWrites) {
    console.log(`flushed: ${entry}`);
  }
  console.log(`exit hook done, code ${code}`);
});
process.on('exit', () => {
  // Timers queued here would never fire: the loop stops after
  // the exit handlers return
  console.log('no async work possible inside exit hooks');
});

代码示例

// Buffered audit entries that a real app would persist somewhere
const pendingWrites = ['login:u1', 'order:42', 'logout:u1'];

// The exit hook runs once, synchronously, right before shutdown.
// Anything async started inside it will never finish, so only
// synchronous flushes belong here.
process.on('exit', (code) => {
  console.log(`exit hook: flushing ${pendingWrites.length} entries`);
  for (const entry of pendingWrites) {
    console.log(`flushed: ${entry}`);
  }
  console.log(`exit hook done, code ${code}`);
});

process.on('exit', () => {
  // Timers queued here would never fire: the loop stops after
  // the exit handlers return
  console.log('no async work possible inside exit hooks');
});

console.log('app work finished, waiting for the loop to drain');