Node.js Command-Line Arguments
Learn how to pass values to a Node.js program through the terminal, access arguments using process.argv, handle missing inputs, convert argument values into numbers, and build reusable command-line applications.
1. Introduction to Command-Line Arguments
Command-line arguments are values supplied to a program when it is started from a terminal. They allow users to provide input without changing the source code every time.
In Node.js, command-line arguments are available through the
process.argv array. This array contains information
about the Node.js executable, the script being executed, and
any additional arguments supplied by the user.
process.argv are strings.
If you need to perform mathematical calculations, convert
numeric arguments into numbers and validate them first.
Why Use Command-Line Arguments?
| Purpose | Example |
|---|---|
| Provide a student name | node app.js Samadhan |
| Choose a course | node app.js Pradnya Node.js |
| Provide numeric input | node calculate.js 10 20 |
| Select an operation | node calculate.js add 10 20 |
| Configure a script's behavior | node report.js summary |
2. How Command-Line Arguments Work
When we execute a Node.js file from the terminal, we can add values after the filename. Node.js makes these values available through the process object.
node app.js Samadhan
process.argv
3. Understand process.argv
The process.argv property is an array containing
the command-line arguments used to start the Node.js process.
In a typical file execution, the first two entries are the
Node.js executable path and the script path.
Example: Display All Arguments
console.log(process.argv);
Execute the Program
node arguments.js Samadhan Node.js
Illustrative Output
[
'C:\\Program Files\\nodejs\\node.exe',
'C:\\Projects\\NodeJsPractice\\arguments.js',
'Samadhan',
'Node.js'
]
The executable and script paths depend on your computer. The additional values are supplied after the script filename.
Argument Index Table
| Index | Meaning | Example Value |
|---|---|---|
process.argv[0] |
Node.js executable path | Path to node.exe |
process.argv[1] |
Executed script path | arguments.js |
process.argv[2] |
First user argument | Samadhan |
process.argv[3] |
Second user argument | Node.js |
2. The exact contents of the first
two entries depend on the runtime invocation.
4. Read a Single Command-Line Argument
Let us create a program that accepts a student name and displays a personalized welcome message.
Step 1: Create welcome.js
const studentName = process.argv[2];
console.log("Welcome to CIIT TRAINING INSTITUTE!");
console.log("Student Name:", studentName);
Step 2: Execute the Program
node welcome.js Samadhan
Expected Output
Welcome to CIIT TRAINING INSTITUTE!
Student Name: Samadhan
Code Explanation
process.argv[2]reads the first user-provided argument.- The value is stored in the
studentNamevariable. console.log()displays the welcome message and name.- Running the same file with a different argument changes the displayed name.
node welcome.js Pradnya and observe how the
output changes without modifying the JavaScript file.
5. Read Multiple Command-Line Arguments
A program can accept multiple arguments. Each argument is
available at a different index in the process.argv
array.
Example: Student and Course Information
const studentName = process.argv[2];
const courseName = process.argv[3];
console.log("Student Name:", studentName);
console.log("Course Name:", courseName);
Execute the Program
node studentCourse.js Pradnya Node.js
Expected Output
Student Name: Pradnya
Course Name: Node.js
How the Values Are Read
process.argv[2]containsPradnya.process.argv[3]containsNode.js.- Spaces separate individual command-line arguments unless the shell groups the text using quotation marks.
6. Pass an Argument Containing Spaces
If an argument contains spaces, use quotation marks around the value in the terminal. This tells the shell to pass the text as a single argument.
Example
const studentName = process.argv[2];
const courseName = process.argv[3];
console.log("Student:", studentName);
console.log("Course:", courseName);
Execute with a Course Name Containing Spaces
node course.js Samadhan ".NET Full Stack Development"
Expected Output
Student: Samadhan
Course: .NET Full Stack Development
7. Convert Command-Line Arguments into Numbers
Command-line arguments are strings, even when they look like numbers. Before performing arithmetic, convert the input into a number and verify that the value is valid.
Example: Add Two Numbers
const firstNumber = Number(process.argv[2]);
const secondNumber = Number(process.argv[3]);
if (
process.argv[2] === undefined ||
process.argv[3] === undefined ||
!Number.isFinite(firstNumber) ||
!Number.isFinite(secondNumber)
) {
console.error("Please provide two valid numbers.");
process.exitCode = 1;
} else {
const total = firstNumber + secondNumber;
console.log("First Number:", firstNumber);
console.log("Second Number:", secondNumber);
console.log("Total:", total);
}
Execute the Program
node add.js 10 20
Expected Output
First Number: 10
Second Number: 20
Total: 30
Try Invalid Input
node add.js 10 hello
Expected Error Message
Please provide two valid numbers.
Explanation
Number()converts the argument into a number.Number.isFinite()checks that the result is a finite number.- The program validates the inputs before adding them.
process.exitCode = 1indicates unsuccessful execution when the program exits.
8. Handle Missing Command-Line Arguments
Users may forget to provide a required argument. A good command-line program should detect missing input and display a clear message rather than silently producing an incorrect result.
Example
const studentName = process.argv[2];
const courseName = process.argv[3];
if (!studentName || !courseName) {
console.error(
"Usage: node studentValidation.js <studentName> <courseName>"
);
process.exitCode = 1;
} else {
console.log("Student:", studentName);
console.log("Course:", courseName);
console.log("Registration details received.");
}
Run Without Arguments
node studentValidation.js
Expected Output
Usage: node studentValidation.js <studentName> <courseName>
Run with Valid Arguments
node studentValidation.js Samadhan "Node.js"
Expected Output
Student: Samadhan
Course: Node.js
Registration details received.
9. Command-Line Argument Processing Flow
Before using command-line values, an application should read the values, check whether required arguments are present, validate their format, and then perform the requested operation.
process.argv
10. Common Mistakes with Command-Line Arguments
| Mistake | Reason | Solution |
|---|---|---|
| Reading index 0 for the first user argument | The first entries normally contain the executable and script paths. | Read the first user argument from index 2. |
| Adding strings instead of numbers | Argument values are strings. | Convert and validate numeric inputs. |
| Not quoting values with spaces | The shell may split the value into multiple arguments. | Wrap the complete value in quotation marks. |
| Using an argument that was not supplied | The selected array index may be undefined. | Check required values before processing. |
| Ignoring invalid input | Incorrect values can produce unexpected results. | Display a helpful error and set a suitable exit code. |
11. CIIT Training Institute - Practice Task
Task: Create a Student Fee Calculator
Create a file named studentFees.js and complete
the following activities:
- Read the student name from a command-line argument.
- Read the first installment amount.
- Read the second installment amount.
- Validate that all required values are provided.
- Convert the installment values into numbers.
- Calculate and display the total fees.
Sample Solution
const studentName = process.argv[2];
const firstInstallment = Number(process.argv[3]);
const secondInstallment = Number(process.argv[4]);
if (
!studentName ||
process.argv[3] === undefined ||
process.argv[4] === undefined ||
!Number.isFinite(firstInstallment) ||
!Number.isFinite(secondInstallment) ||
firstInstallment < 0 ||
secondInstallment < 0
) {
console.error(
"Usage: node studentFees.js <name> <installment1> <installment2>"
);
process.exitCode = 1;
} else {
const totalFees = firstInstallment + secondInstallment;
console.log("CIIT TRAINING INSTITUTE");
console.log("Student:", studentName);
console.log("First Installment:", firstInstallment);
console.log("Second Installment:", secondInstallment);
console.log("Total Fees:", totalFees);
}
Run the Program
node studentFees.js Samadhan 10000 15000
Expected Output
CIIT TRAINING INSTITUTE
Student: Samadhan
First Installment: 10000
Second Installment: 15000
Total Fees: 25000
Try the same program with Pradnya and different installment amounts. The result should change based on the values supplied in the terminal.
Summary
Command-line arguments allow users to provide input when starting a Node.js application. We learned how to read arguments through process.argv, understand array indexes, pass values containing spaces, convert numeric strings, validate missing or invalid input, and build a student fee calculator. These practical concepts at CIIT TRAINING INSTITUTE prepare students to create flexible command-line programs and continue learning about environment variables.