Reputation: 18010
What is the PHP's equivalent of die()/exit()
funciton in Node.js?
https://www.php.net/manual/en/function.exit.php
Upvotes: 66
Views: 26966
Reputation: 93
You can write:
return false
After the block you want halt.
For example:
if(something<=0)
return false;
This will stop the operation. Because JS works on browser you can't stop the page process at certain point. This is re-operable. Use your imagination as requirement to use this.
Upvotes: 0
Reputation: 442
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' }
Upvotes: 0
Reputation: 11832
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.
Upvotes: 5
Reputation: 5840
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);
}
Upvotes: 8
Reputation: 847
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');
Upvotes: 29