node's process argv

2020-08-02

 | 

~3 min read

 | 

408 words

I’ve been exploring Node CLIs lately, which means I needed a better understanding of how all of the wonderful CLIs I use daily work. Specifically, how do they take in all of those flags and options, parse their meaning and function in any order!

Before I start to understand that (because there are tools like Commander that make that part much simpler), I wanted to understand what was going on under the hood with the process.argv.

I’ve written about it briefly in the past in the context of dynamic port assignment for a node server, but today I went to the source.

I’m sure I’ve looked at this a dozen times in the past, but it never clicked. This morning it did - I think.

Let’s take a look.

process.argv

Added in: v0.1.27

  • <string[]>

The process.argv property returns an array containing the command line arguments passed when the > Node.js process was launched. The first element will be process.execPath. See process.argv0 if access to the original value of argv[0] is needed. The second element will be the path to the JavaScript file being executed. The remaining elements will be any additional command line arguments.

For example, assuming the following script for process-args.js:

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

Launching the Node.js process as:

$ node process-args.js one two=three four

Would generate the output:

0: /usr/local/bin/node
1: /Users/mjr/work/node/process-args.js
2: one
3: two=three
4: four

In the javascript file, process-args there’s just one function which is iterating over the array of argv:

process-args.js
process.argv.forEach((val, index) => {
  console.log(`${index}: ${val}`)
})

We can see this full list even more clearly if, instead of parsing each element, we print the whole thing.

Let’s refactor process-args to see this:

console.log(process.argv)

Now when we run the same script:

node process-args.js one two=three four

We get the following output:

[
  '/Users/stephen/.nvm/versions/node/v12.16.2/bin/node',
  '/usr/local/bin/process-args.js',
  'one',
  'two=three',
  'four'
]

NB: The differences between my output and the original is that I use nvm.

At this point we have access to all of the different options. To allow users the flexibility to put their options in any order, we’ll need to add some functionality. More on that later.



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!