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 stringsboolean– string or array of string argument names to always treat as booleanalias– string or array of string argument names to use as aliasesdefault– default values for argumentsstopEarly– populateargv._with everything after the first non-option['--']– populateargv._with everything before--andarv['--']with everything after the--.
It can’t get any easier than that.