loading...

Pass arguments from the command line to a Node script

flaviocopes profile image flavio ⚡️🔥 Originally published at flaviocopes.com on ・1 min read

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 toparse 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

Discussion

pic
Editor guide
Collapse
shane325 profile image
Shane Barry

Alternatively you can do

node app.js NODE_ENV=production

and fetch that in your code

let env = process.env.NODE_ENV

make use of scripts in your package.json file to make this even easier

"scripts": {
    "dev": "node app.js NODE_ENV=development",
    "prod": "node app.js NODE_ENV=production"
  }

now you can run

npm run dev

or

npm run prod

depending on what variable you want

Collapse
kepta profile image
Kushan Joshi

While NODE_ENV works just fine for this case, they aren’t an idiomatic solution for thr passing of information from cli command to program.

Collapse
sugoidesune profile image
Timar
var envs = {  }

process.argv.slice(2).forEach(arg=>{
    var [key,value] =arg.split("=")
    envs[key] = value || true
})

console.log(envs)

>>: node app.js user=john useProduction
>>{
user: 'john',
useProduction: true
}
Collapse
markkoenig95 profile image
MarkKoenig95

Update:

node app.js name=flavio

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

This won't work. It has to be passed in this way

node app.js --name=flavio

Then minimist will parse it correctly