Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

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.

Important Concept: Values received through 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.

User Enters a Terminal Command
node app.js Samadhan
↓
Node.js Starts the Application
↓
Arguments Are Available in process.argv
↓
JavaScript Reads and Validates the Values
↓
Program Displays the Result

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

arguments.js
console.log(process.argv);

Execute the Program

Terminal
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
Remember: For a normal JavaScript file execution, user-provided arguments start at index 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

welcome.js
const studentName = process.argv[2];

console.log("Welcome to CIIT TRAINING INSTITUTE!");
console.log("Student Name:", studentName);

Step 2: Execute the Program

Terminal
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 studentName variable.
  • console.log() displays the welcome message and name.
  • Running the same file with a different argument changes the displayed name.
Try It: Run 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

studentCourse.js
const studentName = process.argv[2];
const courseName = process.argv[3];

console.log("Student Name:", studentName);
console.log("Course Name:", courseName);

Execute the Program

Terminal
node studentCourse.js Pradnya Node.js

Expected Output

Student Name: Pradnya
Course Name: Node.js

How the Values Are Read

  • process.argv[2] contains Pradnya.
  • process.argv[3] contains Node.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

course.js
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

Terminal
node course.js Samadhan ".NET Full Stack Development"

Expected Output

Student: Samadhan
Course: .NET Full Stack Development
Important: The quotation marks group the course name into one argument. The quotation marks themselves are not part of the argument value.

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

add.js
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

Terminal
node add.js 10 20

Expected Output

First Number: 10
Second Number: 20
Total: 30

Try Invalid Input

Terminal
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 = 1 indicates 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

studentValidation.js
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

Terminal
node studentValidation.js

Expected Output

Usage: node studentValidation.js <studentName> <courseName>

Run with Valid Arguments

Terminal
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.

Read Arguments from process.argv
↓
Check Required Arguments
↓
Convert and Validate Values
↓
Perform the Required Operation
↓
Display Result or Error Message
Best Practice: Validate input before using it. This is especially important when command-line arguments control file operations, database tasks, scripts, or other important application behavior.

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:

  1. Read the student name from a command-line argument.
  2. Read the first installment amount.
  3. Read the second installment amount.
  4. Validate that all required values are provided.
  5. Convert the installment values into numbers.
  6. Calculate and display the total fees.
Sample Solution
studentFees.js
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
Terminal
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.