如何停止执行一个node.js脚本?

说我有这个脚本:

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;来实现这一点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.'); } 

但是,这是“正确的”做事的方式吗?

备择scheme

我也见过使用process.exit();例子process.exit();process.exit(1); ,但是这给我一个502 Bad Gateway错误(我假设,因为它杀死节点?)。

callback(); ,这只是给了我一个“未定义”的错误。

什么是“正确”的方式来阻止在任何给定点node.js脚本,并阻止任何下游function执行?

使用return是停止函数执行的正确方法。 你在这个process.exit()是正确的process.exit()会杀死整个节点进程,而不是停止那个单独的函数。 即使你正在使用callback函数,你也要返回它来停止函数的执行。

ASIDE:标准callback是第一个参数是错误的函数,如果没有错误,则为null,所以如果你使用callback,上面的代码如下所示:

 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.'); }