如何停止node.js脚本的执行?
假设我有这个脚本:如何停止node.js脚本的执行?,node.js,exit,Node.js,Exit,假设我有这个脚本: var thisIsTrue = false; exports.test = function(request,response){ if(thisIsTrue){ response.send('All is good!'); }else{ response.send('ERROR! ERROR!'); // Stop script execution here. } console.log
var thisIsTrue = false;
exports.test = function(request,response){
if(thisIsTrue){
response.send('All is good!');
}else{
response.send('ERROR! ERROR!');
// Stop script execution here.
}
console.log('I do not want this to happen if there is an error.');
}
如您所见,如果出现错误,我希望停止脚本执行任何下游函数
我通过添加return实现了这一点代码>发送错误响应后:
var thisIsTrue = false;
exports.test = function(request,response){
if(thisIsTrue){
response.send('All is good!');
}else{
response.send('ERROR! ERROR!');
return;
}
console.log('I do not want this to happen if there is an error.');
}
但这是做事情的“正确”方式吗
备选方案
我还看到了使用process.exit()的示例代码>和过程退出(1)代码>,但这给了我一个502坏网关
错误(我假设是因为它杀死了节点?)
和callback()代码>,这给了我一个“未定义”的错误
在任何给定点停止node.js脚本并阻止任何下游函数执行的“正确”方法是什么?使用返回是停止函数执行的正确方法。您认为进程是正确的。exit()
将杀死整个节点进程,而不仅仅是停止单个函数。即使您正在使用回调函数,您也希望返回它以停止函数执行
旁白:标准回调是一个函数,其中第一个参数为错误,如果没有错误,则为null,因此如果使用回调,则上述情况如下所示:
var thisIsTrue = false;
exports.test = function(request, response, cb){
if (thisIsTrue) {
response.send('All is good!');
cb(null, response)
} else {
response.send('ERROR! ERROR!');
return cb("THIS ISN'T TRUE!");
}
console.log('I do not want this to happen. If there is an error.');
}
您应该使用return
,这将帮助您对发生的事情做出响应。这是一个更简洁的版本,基本上首先验证您想要验证的任何内容,而不是将所有内容封装在if{}else{}语句中
exports.test = function(request, response, cb){
if (!thisIsTrue) {
response.send('ERROR! ERROR!');
return cb("THIS ISN'T TRUE!");
}
response.send('All is good!');
cb(null, response)
console.log('I do not want this to happen. If there is an error.');
}
另一种方法是使用throw
exports.test = function(request, response, cb){
if (!thisIsTrue) {
response.send('ERROR! ERROR!');
cb("THIS ISN'T TRUE!");
throw 'This isn\'t true, perhaps it should';
}
response.send('All is good!');
cb(null, response)
console.log('I do not want this to happen. If there is an error.');
}
最后,将阻止整个应用程序进一步执行的示例:
a) 抛出一个错误,这也将帮助您调试应用程序(如果test()
函数在try{}catch(e){}
中被包装,则不会完全停止应用程序):
抛出新错误(“出错了”)
b) 停止脚本执行(与Node.js一起使用):
process.exit()
您还可以传递相关的退出代码以指示原因
process.exit()//默认退出代码为0,表示*success*
process.exit(1)//未捕获致命异常:存在未捕获异常,并且未由域或“未捕获异常”事件处理程序处理该异常
process.exit(5)//致命错误:V8中有一个不可恢复的致命错误。通常情况下,一条消息将以前缀FATAL ERROR打印到stderr上
更多关于蒂姆·布朗的精彩回答。感谢对标准回调的额外解释。这正是我所需要的