Lesson 12 of 50 – File System Module
24% Completed
24%

Node.js File System (fs) Module

The Node.js File System module allows us to create, read, update, rename, and delete files and directories. It is commonly used in applications that need to store or retrieve information from files.

In simple words: The fs module helps Node.js programs work with files and folders on a computer.

1. What Is the File System Module?

Node.js provides a built-in module called fs. We can use it without installing an additional package.

Some common file operations are:

  • Create a file.
  • Read file contents.
  • Add new content to a file.
  • Replace existing file contents.
  • Rename a file.
  • Delete a file.
  • Create and manage directories.

2. Importing the fs Module

CommonJS Example
const fs = require('node:fs');

console.log("File System Module Loaded");

Output:

File System Module Loaded

The require('node:fs') statement loads the built-in File System module using CommonJS.

ES Modules Example
import fs from 'node:fs';

console.log("File System Module Loaded");

Use this import syntax when your project is configured to use ES Modules.

3. Creating a File with writeFileSync()

The writeFileSync() method writes data to a file synchronously. If the file does not exist, Node.js creates it. If it already exists, its contents are replaced by default.

Example: Create a File
const fs = require('node:fs');

fs.writeFileSync('student.txt', 'Welcome to Node.js');

console.log("File created successfully");

Output:

File created successfully

A file named student.txt is created in the current working directory if it does not already exist.

Important: If the file already exists, this example replaces its previous contents.

4. Reading a File with readFileSync()

The readFileSync() method reads file contents synchronously. Providing 'utf8' returns text instead of a Buffer.

Example: Read a File

Suppose student.txt contains:

Welcome to Node.js

Create app.js:

const fs = require('node:fs');

const data = fs.readFileSync('student.txt', 'utf8');

console.log(data);

Output:

Welcome to Node.js

5. Appending Data with appendFileSync()

The appendFileSync() method adds data to the end of a file. If the file does not exist, it creates the file.

Example: Append Text
const fs = require('node:fs');

fs.appendFileSync('student.txt', '\nLearning File System Module');

console.log("Data appended successfully");

Updated file contents:

Welcome to Node.js
Learning File System Module

The newline character \n moves the appended text to a new line.

6. Updating File Contents with writeFileSync()

You can use writeFileSync() to replace the contents of an existing file with new text.

Example: Replace File Contents
const fs = require('node:fs');

fs.writeFileSync('student.txt', 'Node.js File Updated');

console.log("File updated successfully");

New file contents:

Node.js File Updated
writeFileSync() replaces the existing contents by default. Use appendFileSync() when you want to add text without replacing existing data.

7. Renaming a File with renameSync()

The renameSync() method renames a file or moves it to another location.

Example: Rename a File
const fs = require('node:fs');

fs.renameSync('student.txt', 'student_data.txt');

console.log("File renamed successfully");

Result:

student.txt → student_data.txt

Run this example after creating student.txt. If the source file does not exist, the operation will fail.

8. Deleting a File with unlinkSync()

The unlinkSync() method deletes a file.

Example: Delete a File
const fs = require('node:fs');

fs.unlinkSync('student_data.txt');

console.log("File deleted successfully");

Output:

File deleted successfully
This permanently removes the specified file from its current location. Make sure the file is correct before running the code.

9. Checking Whether a File Exists

The existsSync() method checks whether a path exists. It returns true or false.

Example: Check a File
const fs = require('node:fs');

if (fs.existsSync('student.txt')) {
    console.log("File exists");
} else {
    console.log("File does not exist");
}

The output depends on whether student.txt exists in the current working directory.

In applications that need to handle possible file errors, it is often better to attempt the required operation and handle its error rather than rely on an existence check before acting.

10. Creating a Directory with mkdirSync()

The mkdirSync() method creates a directory. Use the recursive option when parent directories may also need to be created.

Example: Create a Folder
const fs = require('node:fs');

fs.mkdirSync('students', { recursive: true });

console.log("Folder created successfully");

Output:

Folder created successfully

11. Listing Files with readdirSync()

The readdirSync() method returns the names of files and directories inside a directory.

Example: List Directory Contents
const fs = require('node:fs');

const files = fs.readdirSync('.');

console.log(files);

The dot (.) represents the current working directory. The output is an array of entry names, and it depends on the contents of that directory.

12. Synchronous and Asynchronous Methods

The File System module offers synchronous and asynchronous methods. Synchronous methods block execution until the operation finishes. Asynchronous methods allow other JavaScript work to continue while the operation is pending.

Operation Synchronous Method Asynchronous Method
Read a file readFileSync() readFile()
Write a file writeFileSync() writeFile()
Append data appendFileSync() appendFile()
Rename a file renameSync() rename()
Delete a file unlinkSync() unlink()

13. Reading a File Asynchronously

The asynchronous readFile() method uses a callback to receive the file contents or an error.

Example: readFile()
const fs = require('node:fs');

fs.readFile('student.txt', 'utf8', function(err, data) {
    if (err) {
        console.error("Unable to read file:", err.message);
        return;
    }

    console.log(data);
});

console.log("Reading file...");

The message Reading file... can appear before the file contents because the read operation is asynchronous.

Best practice: Asynchronous file operations are generally preferable for server applications when blocking the event loop is undesirable.

14. Practical Assignment

Practice Task
Create a small file management program.
  1. Import the fs module.
  2. Create a file named mydata.txt containing Hello Students.
  3. Read and display the file contents.
  4. Append Welcome to Node.js to the file.
  5. Read the file again and display the updated contents.
  6. Create a directory named myfolder.
  7. List the files in the current directory.

Hint:

const fs = require('node:fs');

fs.writeFileSync('mydata.txt', 'Hello Students');

console.log(fs.readFileSync('mydata.txt', 'utf8'));

fs.appendFileSync('mydata.txt', '\nWelcome to Node.js');

console.log(fs.readFileSync('mydata.txt', 'utf8'));

fs.mkdirSync('myfolder', { recursive: true });

console.log(fs.readdirSync('.'));

🧠 Quiz – Node.js File System Module

Select the correct answer for each question.

1. Which method reads a file synchronously?



2. Which method adds data to the end of a file?



3. Which method deletes a file?