How to take command line arguments in NodeJS?

I am a developer from Delhi, India
Search for a command to run...

I am a developer from Delhi, India
No comments yet. Be the first to comment.
DISCLAIMER: This might not be the most well-written article since I haven't written in a while and I just wanted to get back to writing with a short article about my experience of the day, so sorry about that I previously used this repository for my...

The release of NextJS 13 brought about a plethora of new and impressive features, with one standout being the updated data fetching and management process. The fetch API replaced the more complicated functions, including getServerSideProps, getStatic...

Looking for a safe and reliable way to authenticate users? Consider implementing magic links. They offer a secure alternative to traditional passwords and can help mitigate the risk of password leaks and forgotten passwords. Magic Link authentication...

Neovim is a powerful text editor that can be customized with plugins to enhance its functionality. In this article, we will explore the top 10 essential Neovim plugins. These plugins can help improve your Neovim experience by adding features such as ...

A type-safe and zero-runtime version of Tailwind CSS

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 process.argv.
index.js
console.log(process.argv)
Command Line
node index.js arg1 arg2 arg3
Output
[
'/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 process.argv[2], process.argv[3], etc.
But a nicer way would be to remove the first two elements from the array like so
index.js
const args = process.argv.slice(2)
console.log(args)
Output
[ 'arg1', 'arg2', 'arg3' ]
You can also use this way to take flags from the command line like -s,-o,--help, 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.