Skip to content

Node, accept arguments from the command line

How to accept arguments in a Node.js program passed from the command line

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.

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

→ Get my Node.js Handbook

download all my books for free

  • javascript handbook
  • typescript handbook
  • css handbook
  • node.js handbook
  • astro handbook
  • html handbook
  • next.js pages router handbook
  • alpine.js handbook
  • htmx handbook
  • react handbook
  • sql handbook
  • git cheat sheet
  • laravel handbook
  • express handbook
  • swift handbook
  • go handbook
  • php handbook
  • python handbook
  • cli handbook
  • c handbook

subscribe to my newsletter to get them

Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.

Related posts about node: