AdvancedLesson 10 of 127 min read

Command-Line Tools: Arguments, stdin, stdout and Exit Codes

Build a real command-line tool in Node.js with parseArgs, reading from standard input, writing to standard output and error, using exit codes, and running it in a shell pipeline, with the output verified against Python and standard Unix tools.

In this lesson you will

  • Parse arguments with util.parseArgs
  • Read stdin and write stdout and stderr
  • Return meaningful exit codes
  • Use the tool in a pipeline

About 28 minutes

The morning tool, finished

Mara wants her morning routine to be one command: take the orders export and print the day’s totals. A good command-line tool behaves like the standard Unix programs, so that it can be combined with others. It reads its input from a file named in the arguments, or from standard input when there is none, so that data can be piped in. It writes its results to standard output and its diagnostics to standard error, which keeps results clean when output is redirected to a file. And it ends with an exit code that means something: 0 for success, 2 for wrong usage, 1 for a data error, a convention that scripts rely on.

Node provides what is needed. process.argv holds the arguments, and util.parseArgs, built in since Node 18.3, turns them into options with types, short names and defaults, including a –help flag, so you do not write the parsing by hand. process.stdin is a readable stream, so the tool can read it line by line with readline, and process.stdout and process.stderr are writable streams. Setting process.exitCode, rather than calling process.exit(), lets pending output finish before the process ends, which avoids truncated output when the data goes through a pipe.

Stream Used for Shell
stdin Input data cmd < file, or a pipe
stdout Results cmd > file, or a pipe
stderr Messages for humans cmd 2> errors.txt
Exit code Success or kind of failure $? in a shell
set -u
dir=$(mktemp -d); cd "$dir"
cat > shop.js <<'EOF'
#!/usr/bin/env node
const { parseArgs } = require('node:util');
const readline = require('node:readline');
const fs = require('node:fs');
let args;
try {
  args = parseArgs({ options: { file: { type: 'string', short: 'f' }, top: { type: 'string', short: 't', default: '2' }, help: { type: 'boolean', short: 'h' } } });
} catch (e) { console.error('usage error: ' + e.message); process.exit(2); }
if (args.values.help) { console.log('usage: shop [-f orders.csv] [-t N]   (reads stdin when no file is given)'); process.exit(0); }
const input = args.values.file ? fs.createReadStream(args.values.file) : process.stdin;
input.on('error', e => { console.error('cannot read input: ' + e.code); process.exit(1); });
const rl = readline.createInterface({ input });
const byItem = {}; let bad = 0, rows = 0;
rl.on('line', line => {
  if (!line.trim() || line.startsWith('id,')) return;
  const [id, item, qty, cents] = line.split(',');
  if (!item || !(Number(qty) >= 1) || !(Number(cents) >= 0)) { bad++; console.error('skipping bad line: ' + line); return; }
  rows++; byItem[item] = (byItem[item] || 0) + Number(qty) * Number(cents);
});
rl.on('close', () => {
  const top = Object.entries(byItem).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, Number(args.values.top));
  top.forEach(([k, v]) => console.log(k + ' ' + (v / 100).toFixed(2)));
  console.log('orders ' + rows + ' | total ' + (Object.values(byItem).reduce((a, b) => a + b, 0) / 100).toFixed(2));
  process.exitCode = bad > 0 ? 1 : 0;
});
EOF
cat > orders.csv <<'EOF'
id,item,qty,cents
1,poster,2,1200
2,flyer,100,35
3,card,500,18
4,poster,1,1200
5,banner,1,4500
EOF
echo "# 1 from a file"; node shop.js -f orders.csv; echo "exit: $?"
echo "# 2 from a pipe, top 1"; cat orders.csv | node shop.js --top 1; echo "exit: $?"
echo "# 3 a bad line"; printf 'id,item,qty,cents\n1,poster,2,1200\n2,flyer,x,35\n' | node shop.js 2>err.txt; echo "exit: $?"; echo "stderr was: $(cat err.txt)"
echo "# 4 missing file"; node shop.js -f nothing.csv 2>&1; echo "exit: $?"
echo "# 5 unknown option"; node shop.js --colour red 2>&1 | cut -c1-60; echo "exit: ${PIPESTATUS[0]}"
echo "# 6 help"; node shop.js -h; echo "exit: $?"
echo "# 7 data lines per wc: $(grep -vc '^id,' orders.csv)"
# 1 from a file
card 90.00
banner 45.00
orders 5 | total 206.00
exit: 0
# 2 from a pipe, top 1
card 90.00
orders 5 | total 206.00
exit: 0
# 3 a bad line
poster 24.00
orders 1 | total 24.00
exit: 1
stderr was: skipping bad line: 2,flyer,x,35
# 4 missing file
cannot read input: ENOENT
exit: 1
# 5 unknown option
usage error: Unknown option '--colour'
exit: 2
# 6 help
usage: shop [-f orders.csv] [-t N]   (reads stdin when no file is given)
exit: 0
# 7 data lines per wc: 5
#!/usr/bin/env node
const { parseArgs } = require('node:util');
const readline = require('node:readline');
const fs = require('node:fs');
let args;
try {
  args = parseArgs({ options: { file: { type: 'string', short: 'f' }, top: { type: 'string', short: 't', default: '2' }, help: { type: 'boolean', short: 'h' } } });
} catch (e) { console.error('usage error: ' + e.message); process.exit(2); }
if (args.values.help) { console.log('usage: shop [-f orders.csv] [-t N]   (reads stdin when no file is given)'); process.exit(0); }
const input = args.values.file ? fs.createReadStream(args.values.file) : process.stdin;
input.on('error', e => { console.error('cannot read input: ' + e.code); process.exit(1); });
const rl = readline.createInterface({ input });
const byItem = {}; let bad = 0, rows = 0;
rl.on('line', line => {
  if (!line.trim() || line.startsWith('id,')) return;
  const [id, item, qty, cents] = line.split(',');
  if (!item || !(Number(qty) >= 1) || !(Number(cents) >= 0)) { bad++; console.error('skipping bad line: ' + line); return; }
  rows++; byItem[item] = (byItem[item] || 0) + Number(qty) * Number(cents);
});
rl.on('close', () => {
  const top = Object.entries(byItem).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, Number(args.values.top));
  top.forEach(([k, v]) => console.log(k + ' ' + (v / 100).toFixed(2)));
  console.log('orders ' + rows + ' | total ' + (Object.values(byItem).reduce((a, b) => a + b, 0) / 100).toFixed(2));
  process.exitCode = bad > 0 ? 1 : 0;
});

The shell session ran the tool seven ways. From a file, it printed the top two items by revenue, card 90.00 and banner 45.00, then a totals line of 5 orders and 206.00, and exited with 0. Fed through a pipe, with no file argument, the same code read standard input, and –top 1 limited the list to one line. A file is just one possible source, and the tool does not care where its lines come from, which is what lets Mara chain it after other programs.

The failure cases show the exit codes. A line with a quantity of x was skipped with a message on standard error, which the script redirected to a file, so the results on standard output stay clean, and the exit code was 1, “completed but with data errors”. A missing file gave “cannot read input: ENOENT” and 1 as well. An unknown option, –colour, was rejected by parseArgs and the tool exited with 2, the conventional code for wrong usage, and help printed the usage line and exited with 0. A shell script can tell these apart with the status variable, and decide, for instance, to email Mara only when the code is 1.

Independent check: the revenue per item was recomputed in Python from the same five rows, card 90.00, banner 45.00, poster 36.00, flyer 35.00, and the tool’s lines match for the sorting, the amounts and the grand total of 206.00. The count of data lines, five, was also taken by grep in the shell, a standard Unix tool, and equals the number of orders that the tool reported. The exit codes were read by the shell itself, not by the tool.

Check by hand: 2 x 1,200 + 1 x 1,200 = 3,600 for posters, 100 x 35 = 3,500 for flyers, 500 x 18 = 9,000 for cards and 4,500 for the banner. The total is 3,600 + 3,500 + 9,000 + 4,500 = 20,600 cents, or 206.00, and the order of the top list is cards, banner, posters, flyers by revenue; the output block above shows the result computed by the program.

Do not mix results and messages on stdout

Print results to stdout and warnings and errors to stderr. Otherwise a redirect or a pipe carries your messages into the next program, and breaks it.

Prefer process.exitCode to process.exit()

Calling process.exit() can cut off output that is still being written, especially to a pipe. Set the exit code and let the program end naturally.

About this course

Every program in this lesson was run while the course was written, with Node.js 22 and only its built-in modules (plus the packages named in the lesson), and cross-checked with the shell, curl, Python or the specification. Node.js releases change, so check nodejs.org for the current long-term support version and its documentation. The sh session ran in bash. Windows shells use different syntax for redirection and exit codes, so check your shell’s documentation.

Practice

Add a –min option that hides items below an amount. Make the tool read a gzip file by using zlib in the pipeline. Add the tool to package.json as a bin entry and run it with npx.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

Where should a tool print its results?

  1. stderr
  2. A log file only
  3. stdout
  4. The screen only

Messages go to stderr.

What does exit code 2 conventionally mean?

  1. Success
  2. Wrong usage
  3. Data error
  4. Timeout

0 is success and 1 a general failure.

What does util.parseArgs do?

  1. Reads stdin
  2. Turns command-line arguments into typed options
  3. Runs a child process
  4. Writes files

Built in since Node 18.3.

Why set process.exitCode instead of calling process.exit()?

  1. Pending output can finish
  2. It is shorter
  3. It is faster
  4. It changes colours

Avoids truncated output.

Why read stdin when there is no file argument?

  1. The tool can be used in pipelines
  2. Files are forbidden
  3. It is slower
  4. It is required by Node

The Unix tradition.

Summary

  • A good tool reads files or stdin, writes results to stdout and messages to stderr.
  • Exit codes tell scripts what happened: 0, 1, 2.
  • util.parseArgs handles options.
  • Verify with standard tools and an independent calculation.

Next lesson

Lesson 11 covers worker threads.

Questions

How do I make the script runnable as a command?

Add a shebang line at the top, #!/usr/bin/env node, make the file executable, and for packages add a bin field in package.json.

Should I use a library for command-line parsing?

parseArgs is enough for many tools. Libraries add sub-commands, colours and help generation, so check the current options if you need them.

How do I test a command-line tool?

Run it as a child process with known input and check stdout, stderr and the exit code, as this lesson did, or call its main function directly in unit tests.

Progress is saved in this browser.