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

File System Introduction

The Node.js File System module allows us to create, read, write, update, rename, and delete files and directories. It helps Node.js applications work with data stored on the computer.

For example, a student management application can store student details in a file and read those details whenever required. Node.js provides a built-in module called fs to perform these operations.


1. What Is the File System Module?

The File System module, also known as fs, is a built-in Node.js module used to interact with files and directories.

A file can store information such as student names, employee details, application settings, and text data. Using the fs module, we can perform operations on these files through JavaScript code.

Common file operations include:

  • Creating a new file.
  • Reading existing file content.
  • Writing content into a file.
  • Appending new content to a file.
  • Renaming and deleting files.
  • Creating and reading directories.
Node.js Application
↓
File System Module (fs)
↓
Read and Write Files
Manage Directories

2. Why Do We Use the fs Module?

Applications often need to read or save information. The fs module provides functions to perform these operations.

Requirement Example
Read information Read student details from a text file.
Save information Write application information to a file.
Add information Append a new record to a text file.
Remove a file Delete an unnecessary temporary file.
Manage folders Create a folder for application files.
Remember: The fs module works with the file system available to the Node.js process, subject to operating-system permissions and the environment in which the application runs.

3. Import the fs Module

The fs module is built into Node.js. We do not need to install it separately using npm install.

In a CommonJS project, we can import it using the require() function.

app.js
const fs = require("fs");

console.log("File System module loaded successfully!");

Output:

File System module loaded successfully!

Explanation:

  • require("fs") loads the File System module.
  • const fs stores the module reference in a variable.
  • console.log() displays a message in the terminal.

Using ES Module Syntax

In a project configured to use ES modules, we can import the module using the import statement.

app.js
import fs from "node:fs";

console.log("File System module loaded successfully!");
Note: Use the import syntax that matches your project's module configuration. The examples in this lesson use CommonJS unless specified otherwise.

4. Types of File System Operations

Node.js supports synchronous and asynchronous file operations. These determine how the program behaves while a file operation is being performed.

Operation Type Example Behaviour
Synchronous fs.readFileSync() Blocks further JavaScript execution until the operation completes.
Asynchronous fs.readFile() Allows other JavaScript work to continue while the file operation is handled.

How They Work

Synchronous

Start file operation

↓

Wait until it finishes

↓

Continue execution

Asynchronous

Start file operation

↓

Continue other work

↓

Handle the result when available

Asynchronous methods are generally preferred for file operations in server applications because synchronous operations can block the main JavaScript execution.

5. Common Methods of the fs Module

The fs module provides several methods for handling files and directories.

Method Purpose
fs.readFile() Reads a file asynchronously.
fs.readFileSync() Reads a file synchronously.
fs.writeFile() Creates a file or replaces its content.
fs.appendFile() Adds content to the end of a file.
fs.rename() Renames or moves a file.
fs.unlink() Deletes a file.
fs.mkdir() Creates a directory.
fs.readdir() Reads the contents of a directory.

We will learn these methods with practical examples in the upcoming lessons.

6. Practical Example: Create and Read a File

Let's create a file containing student information and read its content using Node.js.

Step 1: Create a Project Folder

Terminal
mkdir FileSystemDemo
cd FileSystemDemo
npm init -y

Step 2: Create app.js

app.js
const fs = require("fs");

const studentDetails = "Student Name: Rahul\nCourse: Node.js";

fs.writeFile("student.txt", studentDetails, (err) => {
    if (err) {
        console.log("Error writing file:", err.message);
        return;
    }

    console.log("Student file created successfully!");

    fs.readFile("student.txt", "utf8", (readErr, data) => {
        if (readErr) {
            console.log("Error reading file:", readErr.message);
            return;
        }

        console.log("Student Details:");
        console.log(data);
    });
});

Step 3: Run the Application

Terminal
node app.js

Output:

Student file created successfully!
Student Details:
Student Name: Rahul
Course: Node.js

First, fs.writeFile() writes the student information into student.txt. After the write operation succeeds, the callback reads the file using fs.readFile().

Important: fs.writeFile() replaces existing file content by default. Do not use it when you need to preserve the old content; use fs.appendFile() for appending instead.

7. File System Module and NPM

The fs module is included with Node.js, so you do not need to install it separately.

Module Installation Required?
File System (fs) No. It is built into Node.js.
Express Yes. Install it using npm install express.

8. Important Points to Remember

  • fs stands for File System.
  • It is a built-in Node.js module.
  • It supports both synchronous and asynchronous operations.
  • File operations can fail because of missing files or insufficient permissions.
  • Always handle errors in file operations.
  • Use file-writing and deletion methods carefully because they can modify or remove existing data.

9. Practice Task

Task: Create a Student Information File.

  1. Create a folder named StudentInfoApp.
  2. Initialize the project using npm init -y.
  3. Create an app.js file.
  4. Import the fs module.
  5. Write your name, course, and institute into student.txt.
  6. Read the file after writing is complete.
  7. Display the stored information in the terminal.
  8. Handle errors if a file operation fails.

Expected result: A file named student.txt should be created, and its contents should be displayed in the terminal.

Summary

The Node.js File System module, also known as fs, allows applications to work with files and directories. It provides methods for reading, writing, appending, renaming, and deleting files. Since it is a built-in module, we do not need to install it separately.

In this lesson, we learned how to import the fs module, understand synchronous and asynchronous operations, and create and read a student information file. These concepts form the foundation for file handling in Node.js applications at CIIT Training Institute.