Access Command Line Arguments Using process.argv in Node.js

Robin
Updated on February 19, 2023

When we build command-line tools and utilities in Node.js, we often access the command-line arguments and use them to determine what types of actions a user wants to perform.

Node.js provides a way to access the command line arguments using the process.argv property. It is an array that stores all the arguments as strings. We can get any argument from this array using its index.

In this post, you will understand what this process.argv property is, how you can pass arguments to a Node.js application, and how to access those arguments.

We'll also see a simple real-world example that demonstrates how this feature can be used to build a useful command-line tool.

Understanding process.argv in Node.js

When you run a command-line tool or a JavaScript file using Node.js, you can pass the command-line arguments to it. Then you can access those arguments inside the script with the process.argv property.

This property is an array that contains all the argument values as the array items. Here the first item is the path to the Node.js executable, and the second item is the path to the script that you are executing.

If you add any additional arguments when you run your script, those arguments will show up in the process.argv array. You'll find them after the first two items on the array.

How to Pass Command Line Arguments in Node.js

To pass command line arguments in Node.js, all you need to do is specify the arguments after the script name when running the script in the command line. You can pass any number of arguments to your script.

For example, if you have a Node.js script called my-script.js and you want to pass three arguments arg1, arg2 and arg3 to your script.

          node my-script.js arg1 arg2 arg3
        

The arg1, arg2 and arg3 arguments will then be available in the process.argv array in the script, as we discussed earlier. You can pass as many arguments as you want to your script in this way.

Also Read: Easiest Way to Set & Use Environment Variables (.env) in Node.js

Accessing Arguments in Node.js Applications

In the previous section, you have seen how to pass arguments. I passed 3 arguments to the my-script.js file. Now let's see how we can access those arguments inside the my-script.js file.

          // my-script.js

const arguments = process.argv
console.log(arguments)
        

Output:

          [
  '/path/to/node',   // path to the Node.js executable
  '/path/to/my-script.js',  // path to the script being executed
  'arg1',   // first command line argument
  'arg2',   // second command line argument
  'arg3'    // third command line argument
]
        

To access a specific argument, you can simply reference its index in the process.argv array. For example, to access the arg1 argument, you can use process.argv[2], since process.argv[0] and process.argv[1] are the paths to the Node.js executable and the script you are executing, respectively.

You can apply the slice() method to remove the first 2 items from the array and get a new array containing only the command line arguments passed to your script.

          // my-script.js

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

Output:

          [
  'arg1',   // first command line argument
  'arg2',   // second command line argument
  'arg3'    // third command line argument
]
        

As you can see, after applying the slice(2) method on the process.argv array, I am getting a new array that only contains arg1, arg2 and arg3 arguments.

It's important to note that command line arguments are always passed as strings. If you need to use them as numbers or booleans in your script, you'll need to convert them to the appropriate data type.

You can use JavaScript's built-in functions like parseInt() or parseFloat() to convert it to a number. Additionally, it's a good practice to validate the command line arguments passed to your script and handle any errors that may arise.

Also Read: How to Set and Get Cookies in Node.js Express Server

Real-world Example of Using Command Line Arguments

So far You have learned about the process.argv property and how you can access arguments inside the Node.js script using this property. Now let's see an example.

In my example, I have a script that accepts 2 command line arguments. The first argument is a path to a folder and the second argument is the name of a file.

When I execute this script with these 2 arguments, it will check if the file exists or not inside that folder.

          // main.js file

const fs = require('fs').promises

const checkFile = async (path) => {
    try {
        await fs.access(path)
        console.log('File exists')
    } catch (error) {
        // Handle error here
        console.log("File doesn't exists")
    }
}

const filePath = `${process.argv[2]}/${process.argv[3]}`

checkFile(filePath)
        

Here I have a checkFile() function. It takes a path argument, which is the path to the file that we want to check. I am using the fs.access() method to check if the file exists at the given path.

To call this function, I need the path of a file. I am constructing the filePath by joining 2 command line arguments. The process.argv[2] contains folder path and the process.argv[3] contains the file name.

          node main.js ./images banner.jpg
        

Now I am executing the main.js script using Node.js with the 2 arguments. Here "./images" is the folder path and "banner.jpg" is the file name. It will check if the "banner.jpg" file exists or not inside the "images" folder.

Also Read: Node.js Cluster: Improve Server Performance with Clustering

Conclusion

Using command line arguments you can accept options to a command line tool or script and perform different types of actions based on those options. With this feature, you can create more robust and flexible applications that can handle a wide range of inputs.

Whether you're building a simple script or a complex web application, understanding how to work with command-line arguments in Node.js can make your code more efficient, and user-friendly.

Related Posts