exit process with delay

在nodejs中處理error發生要結束process時,可使用process.exit,但注意process.exit會立即返回
特別是當要寫error log時,有可能還沒寫完就結束process了。
這種情況可以利用timer來控制
這裡節錄stackoverflow上的一個解法

Exit Node.js process after event loop is empty OR after timeout

以下節錄

function exit() {
  var t = setTimeout(function() {
    process.exit(1);
  }, 10000);
  // allow process to exist naturally before the timer if it is ready to
  t.unref();
}

如果時間到 event loop不為空,仍然會執行process.exit,中斷未完成的task。
當然這邊會有其他的問題,因為通常發生異常必須結束時,會希望取消其他進行中的async task,單純記上error log,但許多async api並沒有取消的方式。

This entry was posted in nodejs. Bookmark the permalink.

Leave a Reply