如何在 process.exit() 之前在 NodeJS 中发送电子邮件?

How to send email before process.exit() in NodeJS?

我需要在服务器关闭时发送电子邮件,我正在使用 nodemailer,但是当我在 process.exit() 之前写邮件时电子邮件没有发送。

sendMail('Server is shutting down')
process.exit();

我试图使用“beforeExit”事件,但它也不起作用。

The 'beforeExit' event is not emitted for conditions causing explicit termination, such as calling process.exit() or uncaught exceptions.

据我了解,根据文档。

侦听器函数只能执行同步操作。 Node.js 进程将在调用 'exit' 事件侦听器后立即退出,从而导致放弃仍在事件循环中排队的任何其他工作。例如,在下面的示例中,永远不会发生超时:

process.on('exit', (code) => {
  setTimeout(() => {
    console.log('This will not run');
  }, 0);
}); 

在退出事件时需要同步调用,但 nodemailer 是异步的。

节点邮件有回调机制transporter.sendMail(data[, callback]),你可以把它改成Promise 那么您将能够在您的代码中执行此操作:

sendMail('Server is shutting down')
.then(()=>{ 
  process.exit();
})

或者您可以通过将函数转换为异步函数来添加和等待 作为两个解决方案之一的结果 process.exit(); 将仅在 sendMail 函数回调执行后被调用(例如 = 邮件添加到 Postfix 的队列中)