What is the difference between process.exitcode and process.exit() ? If I use process.exitode = 1 and process.exit(1) does this create any difference or its just a alternate way to do ?
2 Answers
Yes, there is a difference.
process.exitCodeonly sets the exit code that will be used when the process eventually exits. It does NOT tell the process to exit, only what code to use when it does.process.exit([code])will terminate the process with the given exit code, or with the value ofprocess.exitCodeif it has been set, or with the exit code 0 (success) by default.
The difference is that exit will exit as quickly as possible (after all 'exit' event listeners are called), even if there are pending async operations, including I/O operations. This can lead to surprising behaviour!
If you don't need to exit as soon as possible or if your code has a lot of async operations, it's safer to use exitCode and let the process exit gracefully when all operations have completed.
Comments
process.exitcode = 1 doesn't do anything consequential. Be careful of capitalisation.
From docs on process.exitCode:
A number which will be the process exit code, when the process either exits gracefully, or is exited via process.exit() without specifying a code.
Thus,
process.exitCode = 1;
// ...
process.exit();
is equivalent to
process.exit(1);
Notably,
process.exitCode = 1;
process.exitCode = 2;
process.exit();
is not equivalent to
process.exit(1);
process.exit(2);
Also,
process.exitCode = 1;
console.log("bye");
process.exit();
is not equivalent to
process.exit(1);
console.log("bye");
8 Comments
process.exitCode = 1 doesn't exit. They both work, but they do different things.process.exit(1); setTimeout(() => { console.log("bye"); }, 2000); It exit the process without printing bye but if i change to process.exitCode = 1 it exit process by printing bye.process.exitCode = 1 doesn't exit. It has nothing to do with asynchronicity. To exit, you need to either call process.exit, or you need to run out of script. Please read the quote again; it says nothing about exiting. Assignment to process.exitCode does not exit. No exiting is happening when you execute process.exitCode = 1.process.exit, because process.exit is abrupt and doesn't allow for things to clean up nicely. Again, process.exitCode = 1 does not exit any more than let x = 3 does; it is a set-up step for the case when the program does end — whether naturally, or by process.exit with no arguments.