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.
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. |
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.
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 fsstores 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.
import fs from "node:fs";
console.log("File System module loaded successfully!");
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
mkdir FileSystemDemo
cd FileSystemDemo
npm init -y
Step 2: Create 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
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().
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
fsstands 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.
- Create a folder named
StudentInfoApp. - Initialize the project using
npm init -y. - Create an
app.jsfile. - Import the
fsmodule. - Write your name, course, and institute into
student.txt. - Read the file after writing is complete.
- Display the stored information in the terminal.
- 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.