Interact with the Command Line using "process.argv" in NodeJS

Interact with the Command Line using "process.argv" in NodeJS

Follow Me on Twitter @AnnaJMcDougall

One of the really cool things I'm discovering about NodeJS is that it allows us to interact more directly with computers, and enables the production of tools using the CLI (Command Line Interface: you may know it as the Terminal).

Just as how yesterday I wrote about the core module fs to achieve some basic file manipulation, today we'll look at one of the big methods in the process core module: argv.

What is the process core module?

This module tends to cover anything involving the actual running of Node scripts. It allows us to do things like terminate the program using process.exit(), for example.

What is argv?

The method process.argv basically captures what the user has typed into the command line or terminal when the programme runs. It returns us an array of each term entered which was separated by a space. If you're familiar with JavaScript string methods, it basically takes the command entered into the terminal, splits it by spaces, and then returns that array.

For example, if we run this code in the Terminal:

$ node index.js a b c

Our process.argv will return:

[
   'C:\\Program Files\\nodejs\\node.exe',
   'C:\\exercises\\index.js',
   'a',
   'b',
   'c'
]

Here we see the path for node, then the path of the file we're running, and then each of the arguments we've entered into the command line.

The really cool thing about this is that it means if we run a simple slice command, we can pull out whatever the user has entered, and then use that in the program they run.

For example, we could make a quick and dirty madlibs like this:

const [name, number, animal, verb] = process.argv.slice(2)

console.log(`${name} was taking a nice stroll 
along the river when suddenly 
${number} ${animal}s appeared and 
began to ${verb}!`)

Line 1 uses destructuring to assign the four words entered by the user to those variables. So now we can enter:

node index.js Bob 42 frog dig

We now have a fun little story pop out the other end:

Bob was taking a nice stroll
along the river when suddenly
42 frogs appeared and
began to dig!

This might seem a relatively silly example, but this allows us access to the command line and to using typed values in our programmes in all sorts of ways, opening up a whole new world of possibilities for creating tools for our fellow developers.