What is the PHP's equivalent of die()/exit() funciton in Node.js?
6 Answers
8 Comments
die() does not terminate the server as Node.js' process.exit() does, it merely stops terminating remaining code in the file. There is no equivalent, unfortunately.process.exit() not stop the server.return if you are not in a function. There are some differences however. See my answer for more details. @MMiller I think this might be more what you mean?require() the library, a simple one-liner is require('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');
7 Comments
throw compared to process.exit() is IMO that you have an error message. The disadvantage (or, sometimes, an advantage), is that it might be catched somewhere. Therefore I wouldn't consider it as a die() equivalent, but as an alternative for many usecases that one should consider.throw and get my catch in order instead of nuking the entire web server.die(), whereas throw would be an equivalent to throw...throwing doesn't support expression usage, therefore you simply can't drop it in everywhere. Well, at least until this proposal lands into language github.com/tc39/proposal-throw-expressionsreject('your die message here') function should be called instead.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:
returnends more graceful.process.exit()more abrupt.returndoes not set the exit code, likeprocess.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.
Comments
You can now use the npm package dump-die.
I took a look at the package on github and it practically uses process.exit(1).
Firstly, install it by npm install dump-die. It has a dd() function.
let foo = 'bar'
let hodor = { hodor: 'hodor' }
dd(foo, hodor)
// returns
// 'bar'
// { hodor: 'hodor' }
php, while such untold primitive things (likeexitand many other things) are not available in those "advanced" languages. in node.js unfotunately, you have toif/returnfrom tens of functions correctly toexit. And moreover, how on earth,return(which should return different value) can be way forexit.. unbelievable.