结束进程时 process.exit() 与 return 有什么区别?

What is the difference between process.exit() vs return when ending the process?

我写了一个在特定条件下结束进程的代码,当我把它写成return时,它由于内存溢出错误而异常结束, 并且 process.exit() 正常结束。

P.S。我的代码只是一个功能。所以两个方法退出一个函数。

能否解释一下这两种方式结束进程的区别?

if(condition === true)
    process.exit();
if(condition === true)
    return;

return 只会停止包含 return 语句的函数。 process.exit 将停止所有 运行 功能并停止所有任务。

所以当你调用return时它会停止当前函数但执行剩余的函数。

  1. 显式调用 process.exit 强制丢弃一些挂起的异步任务。

Calling process.exit() will force the process to exit as quickly as possible even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations to process.stdout and process.stderr.

-- https://nodejs.org/api/process.html#process_process_exit_code

  1. process.exit() 阻止发出 beforeExit 事件。

The 'beforeExit' event is emitted when Node.js empties its event loop and has no additional work to schedule. Normally, the Node.js process will exit when there is no work scheduled, but a listener registered on the 'beforeExit' event can make asynchronous calls, and thereby cause the Node.js process to continue.

-- https://nodejs.org/api/process.html#process_event_exit