0
0
Node.jsframework~5 mins

process.argv for command line arguments in Node.js

Choose your learning style9 modes available
Introduction

We use process.argv to get information typed by the user when starting a Node.js program. It helps the program know what to do based on user input.

You want to let users give options or settings when running your script.
You need to pass file names or data to your program from the command line.
You want to create simple tools that work with different inputs without changing the code.
You want to read flags like --help or --version to show messages.
You want to automate tasks by passing commands to your script.
Syntax
Node.js
const args = process.argv;
// args is an array of strings
// args[0] is the path to the Node.js executable
// args[1] is the path to your script
// args[2] and onwards are the user inputs

process.argv is always an array of strings.

The first two items are fixed: node path and script path. User inputs start from index 2.

Examples
This prints all command line arguments as an array.
Node.js
console.log(process.argv);
This reads the third argument and greets the user by that name.
Node.js
const name = process.argv[2];
console.log(`Hello, ${name}!`);
This skips the first two fixed items and prints each user input on its own line.
Node.js
const args = process.argv.slice(2);
args.forEach(arg => console.log(arg));
Sample Program

This program shows how to read all user inputs after the script name and print them nicely. If no inputs are given, it tells the user.

Node.js
const args = process.argv.slice(2);
if (args.length === 0) {
  console.log('No arguments provided.');
} else {
  console.log('You passed these arguments:');
  args.forEach((arg, index) => {
    console.log(`${index + 1}: ${arg}`);
  });
}
OutputSuccess
Important Notes

Always remember the first two items in process.argv are not user inputs.

Use slice(2) to get only the user arguments.

Arguments are always strings, so convert them if you expect numbers.

Summary

process.argv lets your Node.js program read what the user types when starting it.

The first two items are fixed paths; user inputs start from index 2.

Use slice(2) to get only the user arguments for easier use.