Node, accepts parameters from the command line

How to accept parameters in a Node.js program passed through the command line

When calling a Node.js application with the following command, you can pass any number of parameters

node app.js

Parameters can be independent or have keys and values.

E.g:

node app.js flavio

or

node app.js name=flavio

This will change the way you retrieve this value in the node code.

The way you retrieve it is to useprocessObjects built into Node.

It exposedargvProperty, it is an array containing all command line call parameters.

The first parameter isnodecommand.

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

Starting from the third position, all other parameters are present.

You can use a loop to traverse all parameters (including node path and file path):

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

You can get only the other parameters by creating a new array that excludes the first 2 parameters:

const args = process.argv.slice(2)

If you have a parameter without an index name, for example:

node app.js flavio

you can use it

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

under these circumstances:

node app.js name=flavio

args[0]Yesname=flavio, You need to parse it.

The best way is to useminimistLibrary, which helps to handle parameters:

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

Download mine for freeNode.js manual


More node tutorials: