DEV Community

Kavin Desi Valli
Kavin Desi Valli

Posted on • Originally published at livecode247.com on

How to take command line arguments in NodeJS?

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

Process Object

NodeJS exposes an array of argument values in the form of process.argv.

Example

index.js

console.log(process.argv)

Enter fullscreen mode Exit fullscreen mode

Command Line

node index.js arg1 arg2 arg3

Enter fullscreen mode Exit fullscreen mode

Output

[
  '/usr/local/Cellar/node/16.0.0/bin/node',
  '/Users/username/Code/arg/index.js',
  'arg1',
  'arg2',
  'arg3'
]

Enter fullscreen mode Exit fullscreen mode

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 soindex.js

const args = process.argv.slice(2)
console.log(args)

Enter fullscreen mode Exit fullscreen mode

Output

['arg1', 'arg2', 'arg3']

Enter fullscreen mode Exit fullscreen mode

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 like
yargs`. It can really make this much easier and with lesser code.

Reference

  1. https://nodejs.org/en/knowledge/command-line/how-to-parse-command-line-arguments/

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay