Reporting Usage Errors With an Exit Code

Run without its two arguments, Dev’s Python tool prints how to use it and exits with an error code. Your digest.js now takes the log name and the limit from process.argv.slice(2), but does it refuse a bad command? Until it reads the log, one line stands in for the digest’s work:

Language: JavaScript Filename: digest.js
const args = process.argv.slice(2);
const [path, limit] = args;
const threshold = Number(limit);

console.log(`Checking ${path} against ${threshold}`);

Run it the way Dev does, and then with no arguments at all. Python’s sys.argv[1] would stop with an IndexError there, and unpacking with a ValueError, so predict what the port prints before you look:

Language: Shell
$ node digest.js logs/week-44.log 75
Checking logs/week-44.log against 75
$ node digest.js
Checking undefined against NaN

The second run carries on. Destructuring an empty array doesn’t raise an error. Missing items come back as undefined, and Number(undefined) is NaN. Nothing stops the port, so you have to write the check yourself. In this lesson, you’ll give it the same usage message, in the right place, with an exit code that other programs can read.

Send the Usage Line to Standard Error

Python’s main() starts with a check of the argument count:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.