How to Parse Command line Arguements In NodeJs

Parsing commands The Hard way

In this post I will show you how to parse command line arguments in NodeJs. To process the command line arguments, application will use special javascript object called process.argv.

Create a project folder called node-application with app.js and notes.js files, these files will be used at later stage for adding CURD functionality to the application.

So to display a argument passed to a node application. Inside app.js write console.log(process.argv) to access the command passed to the application. Open terminal in project directory and run the command node app.js command1 and you will get this output in the console.

[
  'C:\\Program Files\\nodejs\\node.exe',
  'C:\\Users\\User 1\\Desktop\\node\\nodeapp\\app.js',
  'command1'
]

Explaining the output:

  • the first line is showing path to node.exe.
  • the second line is showing the the path to javascript file.
  • and the third line is the command which have been passed using node.

In the above output the third line is of our main concern, so to only get the command passed, put the index number of the command which is located at index process.agv[2]. So we will only get the command in output. In general the command will perform some operations on a given data. For example add or remove some data, such as in todo app.

Display the passed command

To display the command passed create a const variable to store the value of process.argv[2]. The below snippet will compare the command with some other conditional value.

 const command=process.argv[2]

 if (command==='add'){
   console.log("adding!")
 }
 else if(command==='remove'){
   console.log("removing!")
 }

so the output for the command node app.js add will display adding! in the console.

Working with command

Now to make full use of command parsing, there should be a specific task a command will do. For example adding a title or removing a title from todo app.

The add command node app.js add --title="New Todo" will try to pass a title, which can be shown by dumping the command.
Running process.argv will give the output.

[
  'C:\\Program Files\\nodejs\\node.exe',
  'C:\\Users\\User1\\Desktop\\node\\nodeapp\\app.js',
  'hello',
  '--title=Adding task'
]

Using plain Javascript to parse the command will make our task difficult, As we have to manually extract data from the command using string methods. To make our jobs easy I will introduce you to Yargs npm package.

const command = process.argv[2]

console.log(process.argv)

if (command === 'add') {
    console.log('Adding note!')
} else if (command === 'remove') {
    console.log('Removing note!')
}

Parsing command using Yargs npm package The easy way

We will use an npm package call yargs to easily parse the commands. Because it will make our task simple and easy to maintain, and save us time to focus on our main application goal.

In the previous step we process the command passed through process.argv. By using this we have to manually extract the key and value and to add command options like --help by own.

Installing Yargs Package

Go to https://www.npmjs.com/package/yargs and install Yargs by npm install yargs.
Load the Yargs library with const yargs = require ('yargs').

Comparing Yargs and Process.argv

Executing command node app.js will give below output as process.argv provide node.exe path and file name while the third line is empty since we did not passed any command, where yargs give underscore and $0 properties which will be explained later.

//javascript
[
  'C:\\Program Files\\nodejs\\node.exe',
  'C:\\Users\\User1\\Desktop\\node\\nodeapp\\app.js'
]

//with yarg
{ _: [], '$0': 'app.js' }

Exploring Yarg Package

To test how yarg works, execute the command node app.js firstCommand --title="Command Title". Pass the command name and title to test the Yarg. We will get a simplified version of output.

{ _: [ 'firstCommand' ], title: 'Command Title', '$0': 'app.js' }

Add Customs Commands using yargs

In this section, Add, Remove, Read, List commands are added. There will be help options for each commands and other options for each command which will be explained later.

Adding "Add" command:

Access the command method of yargs to add new commands and command handler for each.

yargs.command({
  command: 'add',
  description: 'Add a new command',
  handler: function(){
    console.log('Adding a new note')
  }
})

As we have registered a new command so the node app.js --help will give information about it.

Commands:
  app.js add  Add a new command

Options:
  --help     Show help                                    [boolean]
  --version  Show version number               [boolean]

Remove, List and Read commands and their function handlers

//Add
yargs.command({
  command: 'add',
  description: 'Add a new command',
  handler: function(){
    console.log('Adding a new note')
  }
})

//remove
yargs.command({
  command: 'remove',
  description: 'Removing a command',
  handler: function(){
    console.log('Removing a command')
  }
})

//read
yargs.command({
  command: 'read',
  description: 'Read all commands',
  handler: function(){
    console.log("Reading commands")
  }
})

//list
yargs.command({
  command: 'list',
  description: 'Listing commands',
  handler: function(){
    console.log('Listing commands')
  }
})

Complete code till now

app.js

const chalk = require('chalk')
const yargs = require('yargs')
const getNotes = require('./notes.js')

// Customize yargs version
yargs.version('1.1.0')

// Create add command
yargs.command({
    command: 'add',
    describe: 'Add a new note',
    handler: function () {
        console.log('Adding a new note!')
    }
})

// Create remove command
yargs.command({
    command: 'remove',
    describe: 'Remove a note',
    handler: function () {
        console.log('Removing the note')
    }
})

// Create list command
yargs.command({
    command: 'list',
    describe: 'List your notes',
    handler: function () {
        console.log('Listing out all notes')
    }
})

// Create read command
yargs.command({
    command: 'read',
    describe: 'Read a note',
    handler: function () {
        console.log('Reading a note')
    }
})

console.log(yargs.argv)

The next part of this tutorial is Nodejs Arguments Parsing with Yargs Package Part 2. In that section we will JSON and File stream to add and retrieve data from text file.