How to read command line arguments in Nodejs application?


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

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

  • parse with process.argv variable
  • minimist library
  • yargs npm library

How to read command line arguments using process argv variable

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

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

command.js

console.log(process.argv)

And run the above script using below command

node  command.js argument

And output you see is

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

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

First element is node command with complete absolute path second element is file location with absolute path third element is argument is the argument that you passed in terminal

Here is an example to iterate command line arguments with 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 in a nodejs application to parse command line arguments.

First, Install library using below command

npm i yargs

if you want to have typescript support, you can install 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 argument from a command line

First, Install minimist using 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 NodeJS application

  • commander.js
  • meow js
  • vorpal js

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

Similar Posts