Real Dreams
Real Dreams

Reputation: 18010

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

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

Answers (6)

Sohan Arafat
Sohan Arafat

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

MathCoder
MathCoder

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

nl-x
nl-x

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

ekerner
ekerner

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

Anuraag Vaidya
Anuraag Vaidya

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

Uli K&#246;hler
Uli K&#246;hler

Reputation: 13750

process.exit() is the equivalent call.

Upvotes: 83

Related Questions