简体   繁体   中英

What is PHP die() equivalent in Node.js

Node.js中的PHP die()等效是什么?

process.exit()是等效的调用。

I would use throw . Throw will cause the current request at hand to end, and will not terminate the node process. You can catch that output using your error view.

throw new Error('your die message here');

It needs to report to stderr (rather than stdout) and exit with a non-zero status to be die() ...

function die (errMsg) 
{
    if (errMsg)
        console.error(errMsg);
    process.exit(1);
}

If not in a function, you can use:

return;

But you can also use the suggestion of @UliKöhler :

process.exit();

There are some differences:

  • return ends more graceful. process.exit() more abrupt.
  • return does not set the exit code, like process.exit() does.

Example:

try {
    process.exitCode = 1;
    return 2;
}
finally {
    console.log('ending it...'); // this is shown
}

This will print ending it... on the console and exit with exit code 1.

try {
    process.exitCode = 1;
    process.exit(2);
}
finally {
    console.log('ending it...'); // this is not shown
}

This will print nothing on the console and exit with exit code 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM