Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Exit codes

An exit code is a number a program returns to the system when it finishes. 0 means success, any other number means an error. People rarely see it, but build scripts, automated checks and other programs read it to decide whether to continue.

A successful finish

If the program reaches the end without errors, Node.js returns 0 itself:

console.log('Posts checked');

The code of the last command can be checked in the terminal: echo $? in bash, $LASTEXITCODE in PowerShell.

node app.js
echo $?

You see "Posts checked" and then 0.

Reporting an error

Create the file check.js, which checks that a posts file name was passed. If not, the program sets code 1:

// check.js
const file = process.argv[2];
 
if (!file) {
  console.error('Please pass the posts file');
  process.exitCode = 1;
} else {
  console.log(`Checking ${file}`);
}

node check.js prints the message and returns 1, while node check.js posts.json prints "Checking posts.json" and returns 0. Errors are written with console.error(): it prints to a separate error stream that can be redirected apart from normal output.

exitCode and exit()

There are two ways to set the code:

WayWhat happens
process.exitCode = 1The code is remembered, the program finishes its work
process.exit(1)The program stops immediately

Prefer process.exitCode. process.exit() cuts everything off at once: a half-written file or an unsent response stays unfinished.

An unhandled error

If an error happens and nothing catches it, Node.js prints it and returns code 1 itself:

// broken.js
const posts = undefined;
 
console.log(posts.length);

The terminal shows TypeError: Cannot read properties of undefined with the line number, and echo $? shows 1.

Where it helps

In package.json scripts can be chained with &&: the second command runs only if the first returned 0.

{
  "scripts": {
    "deploy": "node check.js posts.json && node build.js"
  }
}

Common mistake

The program printed "Error!" but returned 0 — and an automated check decided everything was fine:

// check.js
if (!process.argv[2]) {
  console.log('Error: no file');
}

A message is not enough. When the program fails at its task, always set process.exitCode = 1.

Thanks for reading!

Donate to the site — we work hard for you.