The Node.js runtime

Node, accept arguments from the command line

Learn how to accept command line arguments in a Node.js program using process.argv, the array that holds every value passed after the node command itself.

You can pass any number of arguments when you start a Node.js application:

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 retrieve the value in your 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}`)
})

Run node app.js flavio and you might see:

0: /usr/local/bin/node
1: /Users/flavio/app.js
2: flavio

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] // 'flavio'

In this case:

node app.js name=flavio

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

The best way to do so is by using the minimist library, which helps dealing with arguments:

const args = require('minimist')(process.argv.slice(2))
args['name'] // 'flavio'

For anything beyond a quick script, I reach for minimist or a dedicated CLI parser. Parsing argv by hand gets messy once you add flags and subcommands.

Try this: save the loop example, run node app.js flavio, and confirm index 2 holds your argument. Then install minimist and parse name=flavio into an object with a name property set to flavio.

Lesson completed