Node.js Command Line Arguments

To access Command Line Arguments in Node.js script file, use process.argv array that contains command line arguments that were passed when starting Node.js process.

Command line arguments are usually used when your program is so generalized and you need to send in some values for the program to work on. A simple example would be a summer which calculates sum of two numbers. You need to provide the two numbers as arguments. Another example would be to load a configuration file. When you start Node.js process, you provide this configuration file to start the application in one of many modes your use cases demand.

In this tutorial, we shall learn how to access Node.js command line arguments with the help of an example.

Example 1 – Read Arguments from Command Line

In this example, we will read command line arguments programmatically using process.argv, and print them to console.

command-line-args-example.js

// process.argv is the array that contains command line arguments
// print all arguments using forEach
process.argv.forEach((val, index) => {
  console.log(`${index}: ${val}`);
});

Output

~$ node command-line-args-example.js argument_one argument_two 3 4 five
0: /usr/local/nodejs/bin/node
1: /home/tutorialkart/workspace/nodejs/command-line-args-example.js
2: argument_one
3: argument_two
4: 3
5: 4
6: five

By default argument 0 is the path to node program and argument 1 is the path to the Node Java Script file. The rest are the additional arguments provided to the Node.js. White space characters are considered as separators for the arguments.

ADVERTISEMENT

Conclusion

In this Node.js Tutorial, we have learnt how to provide and access Command Line Arguments in Node.js script file.