> mthadley_

Node's Built-in Arg Parser

If you’ve ever written a Node program that parsed arguments from the command line, you’ve probably installed a package to do so. Commander and Yargs are old standbys for this. However, this can be a pain for simple, one-off scripts that would otherwise not need a package.json or to depend on globally installed dependencies.

Having spent a lot of time in Ruby land, I appreciated how well stocked the standard library is, which includes an argument parser. So I was pleasantly surprised to discover that Node has one now, too!

It was first added in 16.17.0 as an experimental API, and was fully stabilized in the recent 20.0.0 release. It’s found in the node:util junk-drawer module and you can use it like this:

#!/usr/bin/env node

import { parseArgs } from "node:util"

const options = {
  verbose: {
    type: "boolean",
    default: false,
  },
  name: {
    type: "string",
  },
}

const { values } = parseArgs({ args: process.args, options })

// If run with a `--name michael` argument this will print:
//
//   [Object: null prototype] { name: 'michael', verbose: false }
//
console.log(values)

It’s clearly not as full-featured as the other packages I mentioned, but it was completely serviceable for my last usage.