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

42

假设我有这个脚本:

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();process.exit(1);的例子,但那会导致502 Bad Gateway错误(我猜测是因为它终止了node进程?)。

还有callback();的方式,但那只会给我一个“未定义”的错误。

在任何给定的时刻停止一个node.js脚本并防止任何下游函数执行的“正确”方法是什么?

3个回答

58
使用return是停止函数执行的正确方法。您是正确的,process.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.');

}

1
非常棒的回答@Tim Brown。感谢您对“标准回调”的额外解释。 - AJB

22
您可以使用process.exit()立即强制终止Node.js程序。您还可以传递相关的退出代码以指示原因。
  • process.exit() //默认退出代码为0,表示*成功*

  • process.exit(1) //未捕获的致命异常:发生了未捕获的异常,并且它没有被域或未捕获异常事件处理程序处理

  • process.exit(5) //致命错误:V8中出现了致命不可恢复的错误。通常会在stderr上打印带有前缀FATAL ERROR的消息


更多信息请参见退出代码


1
这正是我所需要的。 - Mahefa

6
你应该使用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){}中,则不会完全停止应用程序):

throw new Error('发生了一些错误')

b)停止脚本执行(适用于Node.js):

process.exit()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接