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

Command-Line Input in Node.js

Learn how to accept input from users and process it in Node.js CLI applications.

1. What Is Command-Line Input?

Command-line input means accepting information from a user through a terminal. For example, a program may ask for a student's name, age, course, or a task description.

In Node.js, we can use the built-in readline module to read input from the terminal. This module provides methods to ask questions and receive the user's responses.

Remember: The program asks a question, the user enters an answer, and Node.js processes that answer.

2. How Command-Line Input Works

The following diagram shows how a CLI application receives and processes information from a user.

Node.js Program

Asks a question

↓
Terminal

Displays the question

↓
User Input

User types an answer

↓
Processing and Output

Program uses the answer and displays a result

3. What Is the Readline Module?

The readline module is a built-in Node.js module used to read data from a readable stream, such as terminal input. It can display questions and receive responses from users.

Because it is built into Node.js, you do not need to install an additional npm package to use it.

Basic Syntax
JavaScript
const readline = require("readline");

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
Understanding the Code
Code Meaning
require("readline") Loads the built-in readline module.
createInterface() Creates an interface for reading and writing.
process.stdin Receives input from the terminal.
process.stdout Displays output in the terminal.

4. Example: Accept the User's Name

Let's create a program that asks the user for their name and displays a welcome message.

Step 1: Create a File

Create a JavaScript file named name.js.

Step 2: Write the Code
name.js
const readline = require("readline");

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question("Enter your name: ", function(name) {
    console.log("Welcome, " + name + "!");
    rl.close();
});
Step 3: Run the Program
Terminal
node name.js
Expected Output
Output
Enter your name: Rahul
Welcome, Rahul!
How Does It Work?

First, rl.question() displays a question in the terminal. The user enters Rahul. The callback function receives the entered name in the name parameter and displays the welcome message. Finally, rl.close() closes the readline interface.

Important: The program waits for the user to enter a response before executing the callback function.

5. Example: Accept Multiple Inputs

We can ask more than one question by placing another rl.question() inside the first question's callback.

Program: Student Details
student.js
const readline = require("readline");

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question("Enter student name: ", function(name) {
    rl.question("Enter course name: ", function(course) {

        console.log("\n--- Student Details ---");
        console.log("Name: " + name);
        console.log("Course: " + course);

        rl.close();
    });
});
Expected Output
Output
Enter student name: Rahul
Enter course name: Node.js

--- Student Details ---
Name: Rahul
Course: Node.js

Here, the application first receives the student's name. Then it asks for the course name. After receiving both inputs, it displays the student details.

Note: In this nested-question example, close the interface after collecting the final input. Closing it too early would prevent the next question from being asked.

6. Multiple Input Flow

This diagram shows the order in which the student details program executes.

Ask Student Name

rl.question()

↓
Store Name in a Parameter

Example: Rahul

↓
Ask Course Name

rl.question()

↓
Display Student Details

Print the name and course

↓
Close Interface

rl.close()

7. Important: User Input Is a String

Values received through rl.question() are strings. If you want to perform mathematical calculations, convert the input to a number first.

Example: Add Two Numbers
addition.js
const readline = require("readline");

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question("Enter first number: ", function(first) {
    rl.question("Enter second number: ", function(second) {

        const num1 = Number(first);
        const num2 = Number(second);

        if (
            first.trim() === "" ||
            second.trim() === "" ||
            !Number.isFinite(num1) ||
            !Number.isFinite(num2)
        ) {
            console.log("Please enter valid numbers.");
        } else {
            console.log("Sum: " + (num1 + num2));
        }

        rl.close();
    });
});
Expected Output
Output
Enter first number: 10
Enter second number: 20
Sum: 30

The Number() function converts the entered strings into numbers. The program then adds the numbers and displays the result. The validation prevents empty or non-numeric entries from being treated as valid numbers.

Remember: "10" + "20" produces "1020" because both values are strings. Using Number("10") + Number("20") produces 30.

8. Important Readline Methods

Method or Property Purpose
readline.createInterface() Creates the readline interface.
rl.question() Displays a question and receives a response.
process.stdin Represents standard input.
process.stdout Represents standard output.
rl.close() Closes the readline interface.

9. Practice Tasks

Task 1: Personal Information

Ask the user for their name, age, and city. Display all three values in the terminal.

Hint: Use three rl.question() calls and close the interface after collecting the final value.

Task 2: Simple Calculator

Ask the user for two numbers and display their sum, difference, and product.

Hint: Convert the input to numbers using Number() before performing calculations.

Summary

Command-line input allows a Node.js application to receive information directly from the user through a terminal. The built-in readline module provides createInterface() to configure terminal input and output, while rl.question() asks questions and receives responses. The rl.close() method closes the interface when input collection is complete.

We learned how to accept a user's name, collect multiple values, and add two numbers after converting string input into numeric values. These skills are useful when building practical CLI projects such as a student record system or a task manager at CIIT Training Institute.