How to take command line arguments in NodeJS?
1 min read
Taking arguments from the command line is very common. You can take certain arguments you need as variables, certain flags, etc. In NodeJS, it's very easy
NodeJS exposes an array of argument values in the form of
node index.js arg1 arg2 arg3
[ '/usr/local/Cellar/node/16.0.0/bin/node', '/Users/username/Code/arg/index.js', 'arg1', 'arg2', 'arg3' ]
The first element of the array is the Node Executable file in your machine. The second element is the file you're running.
You can now take the arguments with indexes 2, 3, 4, etc. like
But a nicer way would be to remove the first two elements from the array like so
const args = process.argv.slice(2) console.log(args)
[ 'arg1', 'arg2', 'arg3' ]
You can also use this way to take flags from the command line like
, etc, like in my [Airtable Url CLI](https://github.com/kavin25/airtable-url-cli).
But, a better way would be to use a third party library likeyargs`. It can really make this much easier and with lesser code.