Categories
JavaScript Nodejs

How to Handle Command Line Arguments in Node Apps

Spread the love

We can use the minimist library to parse command line arguments.

We just have to install minimist by running:

npm i minimist

in our project.

Then, we can use it as follows:

index.js

const argv = require('minimist')(process.argv.slice(2));
console.log(argv);

Now if we run:

node index.js -x 3 -y 4 -n5 -abc --hello=world foo bar baz

We get:

{
  _: [ 'foo', 'bar', 'baz' ],
  x: 3,
  y: 4,
  n: 5,
  a: true,
  b: true,
  c: true,
  hello: 'world'
}

We can pass in an options object with an object that has some options.

The options are passed in as an object with the following properties:

  • string – string or array of string argument names to always treat as strings
  • boolean – string or array of string argument names to always treat as boolean
  • alias – string or array of string argument names to use as aliases
  • default – default values for arguments
  • stopEarly – populate argv._ with everything after the first non-option
  • ['--'] – populate argv._ with everything before -- and arv['--'] with everything after the --.

It can’t get any easier than that.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *