DEV Community

Cover image for 💡 Dealing with command line arguments in Node.js
Benjamin Mock
Benjamin Mock

Posted on • Originally published at

💡 Dealing with command line arguments in Node.js

So you want to use and read command-line arguments in your Node.js application?

So instead of using this to start your application

node app.js

We'll learn how to pass some arguments like this:

node app.js waffles 8

You can access these arguments via the process object, that's built into Node.js. It has an argv property, that contains an array of command-line invocation arguments. Let's see what it contains. We use the above invocation and the following app.js:

process.argv.forEach((value, index) => {
  console.log(`${index}: ${value}`)

For my machine, this is what is logged:

0: /usr/local/bin/node
1: /Users/bm/development/codesnacks/app.js
2: waffles
3: 8

So the first argument is always the full path of the node command itself. The second argument is the full path of the executed js file. But that's not what we're interested in. We're interested in waffles and the amount of them. This is what follows as the third and fourth arguments.

So let's improve our code a bit and get just the relevant arguments by slicing our array accordingly.

const args = process.argv.slice(2)
process.argv.forEach((value, index) => {
  console.log(`${index}: ${value}`)
0: waffles
1: 8

Okay, cool. Now we can use the command-line arguments in our application:

const [pastry, amount] = process.argv.slice(2)
switch (pastry) {
case 'waffles':
    console.log(`Charly Waffles eats ${amount} waffles`)
case 'donuts':
    console.log(`The dog ate ${amount} donuts`)
    console.log('The pastries argument is missing')

And most probably you can write an application that makes more sense than this one 😁

Want to get better at Web Development?
🚀🚀🚀subscribe to the Tutorial Tuesday ✉️newsletter

Top comments (4)

crimsonmed profile image
Médéric Burlet

I have also used a few times yargs it has a lot of features very easy to use and ways to configure it to make sure you don't have to check so much:

benjaminmock profile image
Benjamin Mock

Thanks for sharing!

dytra profile image

I like this ,so basic but powerful ♥

ojolanre_ profile image
The white wolf

I was still getting paths as 0 and 1 until i changed the process.argv into args variable created, this has been good but all of this still seems fuzzy to me