How to read command line arguments in Nodejs application?

This post covers an example of how to read command-line arguments from a nodejs application.

In Nodejs, There are many ways we can read command line parameters from a terminal.

How to read command line arguments using process argv variable

the process is an environment variable to hold nodejs environment information. argv parameter stores command-line information and return an array of command-line arguments.

I have created a simple javascript file and just printed the process.argv

command.js

console.log(process.argv);

And run the above script using the below command

node  command.js argument

And, the output you see is

[ 'C:\\Program Files\\nodejs\\node.exe',
  'B:\\nodeapp\\command.js',
  'argument' ]

As you see, process. argv returning an array of three elements

  • First, the element is a node command with a complete absolute path
  • second, the element is file location with absolute path
  • Finally, the element is argument is the argument that you passed in terminal

Here is an example to iterate command-line arguments with a forEach loop

process.argv.forEach(function (item, index, temp) {
  console.log(index + ": " + item);
});

Output

0: C:\Program Files\nodejs\node.exe
1: B:\nodeapp\command.js
2: kiran

parse command line parameters with yargs

yargs npm is a common and easy-to-use library for writing custom command-line commands. Even though the purpose is different, we could still use a nodejs application to parse command-line arguments.

First, Install the library using the below command.

npm i yargs

if you want to have typescript support, you can install the type definitions as below

npm i @types/yargs --save-dev

Here is the sample code to read command arguments

const yargs = require("yargs/yargs");
const { hideBin } = require("yargs/helpers");
const argv = yargs(hideBin(process.argv)).argv;

console.log(argv);

minimist parse command line arguments

minimist is a simple and easy-to-use library to parse terminal arguments from a command line.

First, Install minimist using the below command

npm i minimist

Here is an example using minimist npm library

var argv = require("minimist")(process.argv.slice(2));
console.log(argv);

and output is

{ "_": ["folder"] }

wrap up

There are below libraries other than minimist and yargs to parse command-line arguments in the NodeJS application

  • commander.js
  • meow js
  • vorpal js

Also documented, we can read without libraries using the process.argv environment variable.