Uli*_*ler 54
process.exit() 是等效的电话.
Anu*_*dya 16
我会用throw.抛出将导致当前的当前请求结束,并且不会终止节点进程.您可以使用错误视图捕获该输出.
throw new Error('your die message here');
Run Code Online (Sandbox Code Playgroud)
它需要向stderr(而不是stdout)报告并以非零状态退出而死()...
function die (errMsg)
{
if (errMsg)
console.error(errMsg);
process.exit(1);
}
Run Code Online (Sandbox Code Playgroud)
如果不在函数中,您可以使用:
return;
Run Code Online (Sandbox Code Playgroud)
但你也可以使用@UliKöhler的建议:
process.exit();
Run Code Online (Sandbox Code Playgroud)
有一些差异:
return结束更优雅.process.exit()更突然.return没有设置退出代码,就像process.exit()没有.例:
try {
process.exitCode = 1;
return 2;
}
finally {
console.log('ending it...'); // this is shown
}
Run Code Online (Sandbox Code Playgroud)
这将ending it...在控制台上打印并退出,退出代码为1.
try {
process.exitCode = 1;
process.exit(2);
}
finally {
console.log('ending it...'); // this is not shown
}
Run Code Online (Sandbox Code Playgroud)
这将在控制台上不打印任何内容并退出,退出代码为2.