NodeJS

Node.js File Operations with Examples (Read, Write, Append, Delete)

📌 INTRODUCTION

File handling is one of the most important features of Node.js. Using Node.js, we can create, read, update, append, rename, and delete files easily.

For file operations, Node.js provides the built-in fs module (fs stands for file system).

In this program, we will learn how to perform common file operations such as:

  • Creating a file
  • Writing data into a file
  • Reading a file
  • Appending data
  • Renaming a file
  • Deleting a file

👉 This is a very important topic for:

  • Practical exams
  • Viva questions
  • Backend development
  • Real-world Node.js applications

📘 PROBLEM STATEMENT

👉 Create a Node.js application to perform various file operations.


💡 CONCEPTS USED

  • Node.js fs module
  • File handling
  • Callback functions
  • Synchronous and asynchronous operations
  • Backend programming basics

🧠 LOGIC EXPLANATION

The program works in the following way:

  1. Import the fs module
  2. Use file system methods like:
    • writeFile()
    • readFile()
    • appendFile()
    • rename()
    • unlink()
  3. Handle results using callback functions
  4. Display success or error messages in the console

💻 PROGRAM CODE

Create a file named fileOperations.js and write the following code:

const fs = require("fs");

// 1. Write data to a file
fs.writeFile("sample.txt", "Hello, this is the first line.\n", (err) => {
if (err) throw err;
console.log("File created and data written successfully.");

// 2. Append data to the file
fs.appendFile("sample.txt", "This line is appended later.\n", (err) => {
if (err) throw err;
console.log("Data appended successfully.");

// 3. Read file contents
fs.readFile("sample.txt", "utf8", (err, data) => {
if (err) throw err;
console.log("File contents:");
console.log(data);

// 4. Rename the file
fs.rename("sample.txt", "newSample.txt", (err) => {
if (err) throw err;
console.log("File renamed successfully.");

// 5. Delete the file
fs.unlink("newSample.txt", (err) => {
if (err) throw err;
console.log("File deleted successfully.");
});
});
});
});
});

▶️ HOW TO RUN THE PROGRAM

Open terminal in your project folder and run:

node fileOperations.js

🖥️ OUTPUT

File created and data written successfully.
Data appended successfully.
File contents:
Hello, this is the first line.
This line is appended later.

File renamed successfully.
File deleted successfully.

🔍 STEP-BY-STEP EXPLANATION

1. Importing the fs Module

const fs = require("fs");

This loads the built-in file system module of Node.js.


2. Writing to a File

fs.writeFile("sample.txt", "Hello, this is the first line.\n", (err) => {
  • Creates a new file if it does not exist
  • Overwrites the file if it already exists

3. Appending Data

fs.appendFile("sample.txt", "This line is appended later.\n", (err) => {
  • Adds new data at the end of the existing file
  • Does not remove old content

4. Reading File Content

fs.readFile("sample.txt", "utf8", (err, data) => {
  • Reads the file content
  • utf8 converts the file into readable text format

5. Renaming a File

fs.rename("sample.txt", "newSample.txt", (err) => {
  • Changes the file name from sample.txt to newSample.txt

6. Deleting a File

fs.unlink("newSample.txt", (err) => {
  • Removes the file permanently from the directory

🎯 IMPORTANT FILE METHODS IN NODE.JS

MethodPurpose
fs.writeFile()Create/write a file
fs.readFile()Read file data
fs.appendFile()Add content to file
fs.rename()Rename a file
fs.unlink()Delete a file

⚡ SIMPLER INDIVIDUAL EXAMPLES

1. Create and Write a File

const fs = require("fs");

fs.writeFile("demo.txt", "Welcome to Node.js file handling!", (err) => {
if (err) throw err;
console.log("File written successfully.");
});

2. Read a File

const fs = require("fs");

fs.readFile("demo.txt", "utf8", (err, data) => {
if (err) throw err;
console.log(data);
});

3. Append to a File

const fs = require("fs");

fs.appendFile("demo.txt", "\nNew line added.", (err) => {
if (err) throw err;
console.log("Data appended.");
});

4. Delete a File

const fs = require("fs");

fs.unlink("demo.txt", (err) => {
if (err) throw err;
console.log("File deleted.");
});

⚠️ SYNCHRONOUS VS ASYNCHRONOUS METHODS

Node.js supports two types of file handling:

Asynchronous

  • Does not block execution
  • Uses callbacks
  • Better for real applications

Example:

fs.readFile("demo.txt", "utf8", (err, data) => {
console.log(data);
});

Synchronous

  • Blocks execution until task finishes
  • Simpler for beginners

Example:

const data = fs.readFileSync("demo.txt", "utf8");
console.log(data);

🌟 ADVANCED VERSION USING SYNCHRONOUS METHODS

const fs = require("fs");

fs.writeFileSync("test.txt", "Node.js File Operations");
console.log("File created.");

fs.appendFileSync("test.txt", "\nAppending more data.");
console.log("Data appended.");

const data = fs.readFileSync("test.txt", "utf8");
console.log("File data:");
console.log(data);

fs.renameSync("test.txt", "updatedTest.txt");
console.log("File renamed.");

fs.unlinkSync("updatedTest.txt");
console.log("File deleted.");

📚 REAL-WORLD USE CASE

Node.js file operations are used in:

  • Logging systems
  • Report generation
  • File uploads
  • Configuration files
  • Reading JSON/data files
  • Saving user activity
  • Exporting results to text or CSV files

❓ VIVA QUESTIONS (IMPORTANT)

Q1. What is the fs module in Node.js?

👉 The fs module is a built-in Node.js module used for file handling operations.


Q2. What is the difference between writeFile() and appendFile()?

👉 writeFile() creates or overwrites a file, while appendFile() adds content to the end of an existing file.


Q3. What does readFile() do?

👉 It reads the contents of a file.


Q4. What is the use of rename()?

👉 It is used to change the name of a file.


Q5. What does unlink() do?

👉 It deletes a file.


Q6. What is the difference between synchronous and asynchronous file methods?

👉 Synchronous methods block execution, while asynchronous methods do not block execution.


Q7. Why is "utf8" used in readFile()?

👉 It converts file data into readable text format.


Q8. Is fs an external package?

👉 No, it is a built-in module in Node.js.


🔗 RELATED POSTS

👉 MCA 168 Full Stack Development Lab Programs List
👉 React Login Form with Validation – Program 19
👉 React Todo List App – Program 18


📌 CONCLUSION

Node.js file operations are essential for backend development. By learning the fs module, you can manage files easily in your applications.

👉 Practice all five operations carefully: write, read, append, rename, and delete. These are frequently asked in practical exams and interviews.


Further Reading

JUnit Tutorial

How to Master Full Stack Development?

Spring Framework Practice Problems and Their Solutions

30 MCQs on JUnit

From Google to the World: The Story of Go Programming Language

Why Go? Understanding the Advantages of this Emerging Language

Creating and Executing Simple Programs in Go

20+ Interview Questions on Go Programming Language

100+ MCQs On Java Architecture

Java Practice Exercise

programmingempire

Princites

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *