How to stop execution of a node.js script?

You can use process.exit() to immediately forced terminate a nodejs program.

You can also pass relevant exit code to indicate the reason.

  • process.exit() //default exit code is 0, which means *success*

  • process.exit(1) //Uncaught Fatal Exception: There was an uncaught exception, and it was not handled by a domain or an 'uncaughtException' event handler

  • process.exit(5) //Fatal Error: There was a fatal unrecoverable error in V8. Typically a message will be printed to stderr with the prefix FATAL ERROR


More on exit codes


Using a return is the correct way to stop a function executing. You are correct in that process.exit() would kill the whole node process, rather than just stopping that individual function. Even if you are using a callback function, you'd want to return it to stop the function execution.

ASIDE: The standard callback is a function where the first argument is an error, or null if there was no error, so if you were using a callback the above would look like:

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

}

Tags:

Exit

Node.Js