Skip to content

.tip

ยท one of the small things

parseArgs instead of reading process.argv by hand

Every repo grows a scripts/ directory where someone slices process.argv and compares strings, and it breaks on the third flag. Node has a parser in the standard library.

import { parseArgs } from "node:util";
 
const { values, positionals } = parseArgs({
  options: {
    env: { type: "string", short: "e", default: "dev" },
    force: { type: "boolean", short: "f" },
  },
  allowPositionals: true,
});

It takes --env=prod, --env prod and -f, and throws on an unknown flag instead of ignoring it. Add multiple: true for one that repeats and you get an array.

nodejstooling