What is PHP exit()/die() equivalent in Node.js

Phpnode.js

Php Problem Overview


Php Solutions


Solution 1 - Php

process.exit() is the equivalent call.

Solution 2 - Php

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

Solution 3 - Php

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);
}

Solution 4 - Php

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.

Solution 5 - Php

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' }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHandsome NerdView Question on Stackoverflow
Solution 1 - PhpUli KöhlerView Answer on Stackoverflow
Solution 2 - PhpAnuraag VaidyaView Answer on Stackoverflow
Solution 3 - PhpekernerView Answer on Stackoverflow
Solution 4 - Phpnl-xView Answer on Stackoverflow
Solution 5 - PhpMathCoderView Answer on Stackoverflow