Menu
CoddyTech

Errors and Exit Codes

Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 5 of 33.

When a command fails, the person at the terminal needs to see why, and any program that ran yours needs to know it failed.

A program has two output streams: stdout for results and stderr for errors, written with console.error. When it ends it hands back an exit code: 0 means it worked, anything else means it failed. process.exit(1) stops the program at once with code 1.

// node divide.js 6 0
const [a, b] = process.argv.slice(2).map(Number);
if (b === 0) {
    console.error('Cannot divide by zero');
    process.exit(1);
}
console.log(a / b);

The terminal beside your code shows stderr in red and prints the exit code when it is not 0.

challenge icon

Challenge

Easy

When someone uses your tool wrongly, it should say how to use it and tell the terminal that it failed. Programs do this with the error stream, stderr, and an exit code.

  1. In notes.js, change the final else branch, the one that prints Unknown command:. Errors go to stderr, so print them with console.error instead of console.log.
  2. When a command was typed but is unknown, print these two lines to stderr, in this order:
    Unknown command: remove
    Usage: node notes.js <command> [words]
    The first line names the word that was typed: here remove, from node notes.js remove 3. The second line is always the same. Copy it exactly, with <command> and [words] as written: they are part of the text, not something to fill in.
  3. When nothing was typed after node notes.js, print only the usage line to stderr. Do not print Unknown command: undefined.
  4. In both cases, end the program with exit code 1, which means "it failed".
  5. add and list work as before. node notes.js add Buy milk still prints Adding: Buy milk and ends with exit code 0.

Try it: press Run with the box after $ node notes.js empty. You see the usage line in red, and the terminal shows exit code 1. Then type remove 3 and press Enter: you see Unknown command: remove and the usage line, both in red, and exit code 1. Then type add Buy milk: you see Adding: Buy milk in the normal color, and no exit code, because the terminal hides a 0.

Try it yourself

// Your notes tool starts here.
const [command, ...words] = process.argv.slice(2);
const text = words.join(' ');

if (command === 'add') {
    console.log(`Adding: ${text}`);
} else if (command === 'list') {
    console.log('No notes yet');
} else {
    console.log(`Unknown command: ${command}`);
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Node.js Basics

Practice on your own: Express playground