Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readNode

Parse CLI flags with util.parseArgs

Use util.parseArgs to read long flags, short flag clusters and filenames, then validate numeric values at the command line.

Your image script reads a filename from process.argv[2]. Once you add flags, a lookup for --width misses --width=1200 and lets typos pass. parseArgs from node:util parses flags from a description you write once, and it has been stable since Node 20.

Describe the flags, get an object back

Save this as resize.mjs. Each key in options is a long flag name. Give it a type, and optionally a one-letter short, a default, or multiple: true to collect repeats into an array.

import { parseArgs } from 'node:util'

const options = {
  width: { type: 'string', short: 'w', default: '800' },
  out: { type: 'string', short: 'o', default: 'dist' },
  tag: { type: 'string', multiple: true },
  verbose: { type: 'boolean', short: 'v' },
}

const { values, positionals } = parseArgs({ options, allowPositionals: true })

console.log(values, positionals)

With no args it reads process.argv minus the node path and the script name. allowPositionals: true lets the file names through, and without it a.png throws Unexpected argument 'a.png'.

Run it with the spellings people type

$ node resize.mjs -v --width=1200 --tag hero --tag og a.png b.png
[Object: null prototype] {
  verbose: true,
  width: '1200',
  tag: [ 'hero', 'og' ],
  out: 'dist'
} [ 'a.png', 'b.png' ]

$ node resize.mjs -vw 640 a.png
[Object: null prototype] { verbose: true, width: '640', out: 'dist' } [ 'a.png' ]

$ node resize.mjs --widht 1200 a.png
TypeError [ERR_PARSE_ARGS_UNKNOWN_OPTION]: Unknown option '--widht' …

The same object comes back for --width=1200 and --width 1200, the -vw 640 cluster splits into both flags, and the typo stops the script. A file name that starts with a dash goes after --.

Strings and booleans, so convert numbers yourself

A type is 'string' or 'boolean' and nothing else, so width arrives as '1200'. A default only applies when the flag is absent from the command line.

The thrown error comes with a Node stack trace, which is noise for someone who mistyped a flag. Keep the imports and options, then replace everything from the parseArgs call onward with this block. It prints a usage line for parse errors and accepts widths written as decimal digits.

let args
try {
  args = parseArgs({ options, allowPositionals: true })
} catch (err) {
  console.error(`${err.message}\nusage: resize [-v] [-w px] [-o dir] <files...>`)
  process.exit(2)
}

const rawWidth = args.values.width
const width = Number(rawWidth)
if (!/^\d+$/.test(rawWidth) || !Number.isSafeInteger(width) || width <= 0) {
  console.error(`--width must be a positive whole number, got '${args.values.width}'`)
  process.exit(2)
}

Now --widht prints the message and the usage line instead of a stack, and -w 12OO, with the letter O typed for zeros, fails with got '12OO' before any image is touched. A boolean given a value, --verbose=yes, fails the same way with does not take an argument.