Almost every backend application interacts with files.
Think about some common examples:
- Reading a configuration file
- Uploading profile images
- Saving logs
- Reading JSON data
- Creating reports
- Downloading files
- Managing user documents
Without the ability to work with files, building real-world applications would be nearly impossible.
This is where the File System (FS) module comes in.
The FS module is one of the most important built-in modules in Node.js. It allows developers to create, read, update, delete, copy, move, and manage files and directories.
In this article, we'll learn the FS module step by step with practical examples.
Let's get started!
What is the FS Module?
The FS (File System) module is a built-in Node.js module that provides APIs for interacting with the file system.
Using the FS module, you can:
- Create files
- Read file contents
- Update files
- Delete files
- Rename files
- Copy files
- Move files
- Create folders
- Read folder contents
- Delete folders
- Check file information
Since it's built into Node.js, you don't need to install anything.
Simply import it.
const fs = require("fs");
Or, if you're using ES Modules:
import fs from "node:fs";
Why Do We Need the FS Module?
Imagine you're building a blogging application.
Every time a user uploads an image, your backend must:
- Store the image
- Save its location
- Read it later
- Delete it if necessary
Or imagine building a logging system.
Every API request should be written into a log file.
All these tasks are possible because of the File System module.
File System Operations
The most common file operations are:
- Create File
- Read File
- Update File
- Append Data
- Rename File
- Delete File
- Create Folder
- Read Folder
- Delete Folder
Let's understand each one.
Creating a File
Create a file named:
app.js
Import the FS module.
const fs = require("fs");
Create a new file.
const fs = require("fs");
fs.writeFileSync("hello.txt", "Welcome to Node.js!");
console.log("File Created Successfully");
Run:
node app.js
Output:
File Created Successfully
A new file called hello.txt is created in your project folder.
Understanding writeFileSync()
fs.writeFileSync(fileName, data);
Parameters
- fileName → Name of the file
- data → Content to write
If the file doesn't exist, Node.js creates it.
If it already exists, its contents are replaced.
Reading a File
Now let's read the file we created.
const fs = require("fs");
const data = fs.readFileSync("hello.txt", "utf-8");
console.log(data);
Output:
Welcome to Node.js!
Why Do We Use "utf-8"?
Without specifying the encoding:
const data = fs.readFileSync("hello.txt");
console.log(data);
Output:
<Buffer 57 65 6c 63 6f ...>
Node.js returns a Buffer by default.
Adding "utf-8" converts the data into a readable string.
Appending Data
Suppose you don't want to overwrite the file.
Instead, you want to add more content.
const fs = require("fs");
fs.appendFileSync("hello.txt", "\nLearning the FS Module");
console.log("Content Added");
File Content:
Welcome to Node.js!
Learning the FS Module
Overwriting a File
If you use writeFileSync() again:
fs.writeFileSync("hello.txt", "New Content");
The file becomes:
New Content
The previous content is lost.
Renaming a File
const fs = require("fs");
fs.renameSync("hello.txt", "notes.txt");
console.log("File Renamed");
Output:
File Renamed
Now the file is named notes.txt.
Deleting a File
const fs = require("fs");
fs.unlinkSync("notes.txt");
console.log("File Deleted");
Output:
File Deleted
The file is permanently removed.
Creating a Folder
const fs = require("fs");
fs.mkdirSync("documents");
console.log("Folder Created");
Project Structure:
project/
├── app.js
├── documents/
Reading Folder Contents
const fs = require("fs");
const files = fs.readdirSync(".");
console.log(files);
Output:
[
"app.js",
"documents",
"package.json"
]
This returns an array of files and folders.
Deleting a Folder
If the folder is empty:
const fs = require("fs");
fs.rmdirSync("documents");
console.log("Folder Deleted");
Note: In recent Node.js versions,
rmdirSync()is intended for empty directories. To remove a directory and all its contents, usefs.rmSync("documents", { recursive: true, force: true }).
Copying a File
Create a file.
hello.txt
Content:
Welcome to Node.js
Now copy it.
const fs = require("fs");
fs.copyFileSync("hello.txt", "backup.txt");
console.log("File Copied");
Output:
File Copied
Now you have:
hello.txt
backup.txt
Both contain the same content.
Checking Whether a File Exists
const fs = require("fs");
const exists = fs.existsSync("hello.txt");
console.log(exists);
Output:
true
If the file doesn't exist:
false
Getting File Information
const fs = require("fs");
const stats = fs.statSync("hello.txt");
console.log(stats);
Example Output:
Stats {
size: 25,
birthtime: ...
}
Useful File Information
Check file size.
const stats = fs.statSync("hello.txt");
console.log(stats.size);
Output:
25
Check whether it's a file.
console.log(stats.isFile());
Output:
true
Check whether it's a folder.
console.log(stats.isDirectory());
Output:
false
Reading JSON Files
Suppose you have:
student.json
{
"name": "John",
"age": 22
}
Read it.
const fs = require("fs");
const data = fs.readFileSync("student.json", "utf-8");
const student = JSON.parse(data);
console.log(student);
Output:
{
name: "John",
age: 22
}
This is very common in Node.js applications.
Writing JSON Files
const fs = require("fs");
const student = {
name: "Emma",
age: 21,
};
fs.writeFileSync(
"student.json",
JSON.stringify(student, null, 2)
);
console.log("JSON Saved");
Output:
JSON Saved
Generated file:
{
"name": "Emma",
"age": 21
}
Build a Simple Notes Application
const fs = require("fs");
fs.writeFileSync("notes.txt", "Node.js Notes");
fs.appendFileSync(
"notes.txt",
"\nLearning FS Module"
);
const notes = fs.readFileSync(
"notes.txt",
"utf-8"
);
console.log(notes);
Output:
Node.js Notes
Learning FS Module
Commonly Used FS Methods
writeFileSync() - Create or overwrite a file
readFileSync() - Read a file
appendFileSync() - Append data
renameSync() - Rename a file
unlinkSync() - Delete a file
mkdirSync() - Create a folder
rmdirSync() - Delete an empty folder
rmSync() - Delete files or folders (including non-empty folders with options)
readdirSync() - Read folder contents
copyFileSync() - Copy a file
existsSync() - Check if a file exists
statSync() - Get file information
Real-World Use Cases
The FS module is widely used for:
- Image uploads
- PDF generation
- Log files
- Configuration files
- JSON databases
- Report generation
- Backup utilities
- Static file management
Almost every backend project uses the File System module in some way.
Best Practices
When working with the FS module:
- Always check whether a file exists before performing sensitive operations when appropriate.
- Use
try...catchto handle unexpected errors. - Use
"utf-8"when reading text files. - Avoid hardcoding file paths; combine the FS module with the Path module.
- Prefer asynchronous or Promise-based FS APIs in production web servers to avoid blocking the event loop.
Common Beginner Mistakes
Here are some common mistakes developers make:
- Forgetting to specify the file encoding.
- Using
writeFileSync()when they intended to append data. - Trying to delete a file that doesn't exist.
- Assuming
readFileSync()returns a string without specifying an encoding. - Using synchronous file operations inside high-traffic server routes.
Final Thoughts
The FS (File System) module is one of the core modules you'll use throughout your Node.js journey. It provides everything you need to manage files and directories, making it essential for building real-world backend applications.
In this article, you learned:
- What the FS module is
- How to create files
- How to read file contents
- How to update and append data
- How to rename and delete files
- How to create and delete folders
- How to read JSON files
- How to copy files
- How to retrieve file information
Mastering the FS module is an important step toward building production-ready Node.js applications.
Happy Coding! 🚀