How do I pass command line arguments to a Node.js program and receive them?

Better Stack Team
Updated on March 11, 2024

In Node.js, you can pass command line arguments to your script the same as you would for any other command line application. Simply type your arguments after the script path separated with a space as shown below:

 
node task.js foo bar

Then you can retrieve the arguments from the process.argv array like this:

 
process.argv.forEach((val, index) => {
  console.log(index + ': ' + val);
});

The first element (index 0) is always a path to your Node.js executable and the second element (index 1) is a path to your script. Additional elements are the ones you pass when executing the script. In the case of the example above. The process.argv array would look something like this:

 
0: /path/to/node
1: /path/to/task.js
2: foo
3: bar

You can also use packages such as commander, yargs or minimist to help you handle and parse command line arguments.

Remember, command line arguments are string so you need to convert them to other types when necessary.