Node, accept arguments from the command line

By

Learn how to accept command line arguments in Node.js with process.argv, the built-in util.parseArgs parser, and optional libraries like minimist.

~~~

You can pass any number of arguments when invoking a Node.js application using

node app.js

Arguments can be standalone or have a key and a value.

For example:

node app.js flavio

or

node app.js name=flavio

This changes how you will retrieve this value in the Node code.

The way you retrieve it is using the process object built into Node.

It exposes an argv property, which is an array that contains all the command line invocation arguments.

The first argument is the full path of the node command.

The second element is the full path of the file being executed.

All the additional arguments are present from the third position going forward.

You can iterate over all the arguments (including the node path and the file path) using a loop:

process.argv.forEach((val, index) => {
  console.log(`${index}: ${val}`)
})

You can get only the additional arguments by creating a new array that excludes the first 2 params:

const args = process.argv.slice(2)

If you have one argument without an index name, like this:

node app.js flavio

you can access it using

const args = process.argv.slice(2)
args[0]

In this case:

node app.js name=flavio

args[0] is name=flavio, and you need to parse it.

Built-in parsing with util.parseArgs

Since Node 20, parseArgs from node:util is the built-in way to parse flags. No extra package needed:

import { parseArgs } from 'node:util'

const { values, positionals } = parseArgs({
  options: {
    name: {
      type: 'string',
    },
  },
  allowPositionals: true,
})

console.log(values.name)
console.log(positionals)

Run it with:

node app.js --name flavio

values.name is flavio. Positional args land in positionals.

Notice the double dashes. parseArgs expects --name flavio or --name=flavio. A bare name=flavio is not a flag, so it ends up in positionals as a string.

You can also pass args: process.argv.slice(2) yourself if you want to feed the parser a custom array. By default it already skips the node path and the script path.

Third-party alternative: minimist

If you prefer a library, minimist is still a solid option:

import minimist from 'minimist'

const args = minimist(process.argv.slice(2))
args.name //flavio

It expects the same double-dash syntax: node app.js --name=flavio. Useful when you already depend on it. For new code, start with util.parseArgs.

Tagged: Node.js · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about node: