Errors and Exit Codes
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 4 of 24.
When a command fails, the terminal and the scripts that call your program need to know.
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
Easy- With no command, print
Usage: node notes.js <command> [words]to stderr and exit with code1. - An unknown command prints
Unknown command: <word>and then the usage line, both to stderr, and exits with1.
Run node notes.js, then node notes.js remove 3.
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, NodeCommand-Line ArgumentsCommands