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
EasyWhen 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.
- In
notes.js, change the finalelsebranch, the one that printsUnknown command:. Errors go to stderr, so print them withconsole.errorinstead ofconsole.log. - When a command was typed but is unknown, print these two lines to stderr, in this order:The first line names the word that was typed: here
Unknown command: remove Usage: node notes.js <command> [words]remove, fromnode 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. - When nothing was typed after
node notes.js, print only the usage line to stderr. Do not printUnknown command: undefined. - In both cases, end the program with exit code 1, which means "it failed".
addandlistwork as before.node notes.js add Buy milkstill printsAdding: Buy milkand 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}`);
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Node.js Basics
1Running JavaScript on Node
Hello, NodeReading the CommandCommand-Line ArgumentsCommandsPractice on your own: Express playground