One of the most common tasks in backend development is working with files.
Whether you're building a blogging platform, an e-commerce application, or a chat application, you'll often need to:
- Read configuration files
- Save uploaded images
- Generate reports
- Store logs
- Read JSON data
- Create backups
Node.js provides a powerful File System (FS) module for handling these operations.
Interestingly, Node.js offers three different ways to perform file operations:
- Synchronous APIs
- Callback APIs
- Promise APIs
Although all three can accomplish the same tasks, they differ in how they execute and how they affect your application's performance.
In this article, we'll explore each approach with practical examples and learn when to use them.
Let's get started!
What is the File System (FS) Module?
The File System (FS) module is a built-in Node.js module that allows you to interact with files and directories.
Using the FS module, you can:
- Create files
- Read files
- Update files
- Delete files
- Rename files
- Copy files
- Create folders
- Delete folders
- Read folder contents
Since it's built into Node.js, you don't need to install anything.
1. File System Synchronous APIs
What are Synchronous APIs?
Synchronous APIs execute one task at a time.
The next line of code waits until the current file operation finishes.
Think of it like waiting in a queue.
Task 1
↓
Wait...
↓
Task 2
↓
Wait...
↓
Task 3
Everything happens sequentially.
Import the FS Module
const fs = require("fs");
Step 1: Create a 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 named hello.txt is created.
Step 2: Read a File
const fs = require("fs");
const data = fs.readFileSync("hello.txt", "utf-8");
console.log(data);
Output:
Welcome to Node.js!
Notice that the application waits until the file is completely read before moving to the next line.
Step 3: Append Data
const fs = require("fs");
fs.appendFileSync("hello.txt", "\nLearning Node.js");
console.log("Content Added");
File Content:
Welcome to Node.js!
Learning Node.js
Step 4: Rename the File
const fs = require("fs");
fs.renameSync("hello.txt", "notes.txt");
console.log("File Renamed");
Step 5: Delete the File
const fs = require("fs");
fs.unlinkSync("notes.txt");
console.log("File Deleted");
Understanding Blocking Behavior
Consider this example.
const fs = require("fs");
console.log("Start");
const data = fs.readFileSync("hello.txt", "utf-8");
console.log(data);
console.log("End");
Output:
Start
Welcome to Node.js!
End
The application waits until the file is completely read.
This is why synchronous APIs are called blocking APIs.
When Should You Use Synchronous APIs?
Synchronous APIs are useful for:
- Command-line tools
- Startup configuration
- Automation scripts
- Small utilities
- Learning purposes
Avoid them inside web servers because they block the event loop.
2. File System Callback APIs
What are Callback APIs?
Callback APIs are asynchronous.
Instead of waiting for a file operation to finish, Node.js continues executing the remaining code.
Once the operation completes, a callback function is executed.
Write a File
const fs = require("fs");
fs.writeFile("hello.txt", "Welcome to Node.js!", (error) => {
if (error) {
console.log(error);
return;
}
console.log("File Created");
});
Output:
File Created
Read a File
const fs = require("fs");
fs.readFile("hello.txt", "utf-8", (error, data) => {
if (error) {
console.log(error);
return;
}
console.log(data);
});
Output:
Welcome to Node.js!
Understanding Asynchronous Execution
const fs = require("fs");
console.log("Start");
fs.readFile("hello.txt", "utf-8", (error, data) => {
console.log(data);
});
console.log("End");
Output:
Start
End
Welcome to Node.js!
Notice something interesting?
The application doesn't wait for the file to be read.
Instead:
- Starts reading the file.
- Continues executing the next line.
- Prints the file contents when reading is complete.
This is why callback APIs are called non-blocking APIs.
Callback Hell
Suppose we want to:
- Create a file
- Read it
- Rename it
- Delete it
Using callbacks:
const fs = require("fs");
fs.writeFile("demo.txt", "Hello", (err) => {
if (err) return console.log(err);
fs.readFile("demo.txt", "utf-8", (err, data) => {
if (err) return console.log(err);
console.log(data);
fs.rename("demo.txt", "notes.txt", (err) => {
if (err) return console.log(err);
fs.unlink("notes.txt", (err) => {
if (err) return console.log(err);
console.log("Completed");
});
});
});
});
This nested structure is difficult to read and maintain.
This problem is known as Callback Hell.
When Should You Use Callback APIs?
Use callback APIs when:
- Working with legacy Node.js projects
- Maintaining older codebases
- Using libraries that rely on callbacks
For modern applications, Promise APIs are generally a better choice.
3. File System Promise APIs
What are Promise APIs?
Promise APIs are asynchronous, just like callback APIs.
However, instead of callbacks, they return Promises, making them easy to use with async/await.
This results in cleaner and more readable code.
Import Promise APIs
const fs = require("fs/promises");
Write a File
const fs = require("fs/promises");
async function createFile() {
await fs.writeFile("hello.txt", "Welcome to Node.js");
console.log("File Created");
}
createFile();
Read a File
const fs = require("fs/promises");
async function readFile() {
const data = await fs.readFile("hello.txt", "utf-8");
console.log(data);
}
readFile();
Output:
Welcome to Node.js
Append Data
const fs = require("fs/promises");
async function appendData() {
await fs.appendFile("hello.txt", "\nLearning Promise APIs");
console.log("Content Added");
}
appendData();
Rename a File
const fs = require("fs/promises");
async function renameFile() {
await fs.rename("hello.txt", "notes.txt");
console.log("Renamed");
}
renameFile();
Delete a File
const fs = require("fs/promises");
async function deleteFile() {
await fs.unlink("notes.txt");
console.log("Deleted");
}
deleteFile();
Error Handling with try...catch
Always use try...catch with Promise APIs.
const fs = require("fs/promises");
async function readData() {
try {
const data = await fs.readFile("hello.txt", "utf-8");
console.log(data);
} catch (error) {
console.log(error.message);
}
}
readData();
Build a Complete CRUD Example
const fs = require("fs/promises");
async function main() {
try {
await fs.writeFile("student.txt", "John");
const data = await fs.readFile("student.txt", "utf-8");
console.log(data);
await fs.appendFile("student.txt", "\nAge: 22");
await fs.rename("student.txt", "user.txt");
console.log("Operations Completed");
await fs.unlink("user.txt");
console.log("File Deleted");
} catch (error) {
console.log(error.message);
}
}
main();
Output:
John
Operations Completed
File Deleted
Notice how much cleaner this code is compared to nested callbacks.
Comparison of All Three APIs
Let's perform the same operation using all three approaches.
Synchronous API
const fs = require("fs");
const data = fs.readFileSync("hello.txt", "utf-8");
console.log(data);
Simple, but blocks execution.
Callback API
const fs = require("fs");
fs.readFile("hello.txt", "utf-8", (err, data) => {
console.log(data);
});
Asynchronous, but callback-based.
Promise API
const fs = require("fs/promises");
async function main() {
const data = await fs.readFile("hello.txt", "utf-8");
console.log(data);
}
main();
Asynchronous and easy to read.
Which API Should You Use?
Use Synchronous APIs
- CLI Tools
- Automation Scripts
- Startup Configuration
- Learning
Use Callback APIs
- Legacy Projects
- Older Libraries
- Existing Callback-Based Code
Use Promise APIs
- Express Applications
- REST APIs
- Modern Node.js Projects
- Production Applications
- Microservices
This is the recommended approach for most new Node.js applications.
Best Practices
When working with File System APIs:
- Prefer Promise APIs with
async/awaitfor modern applications. - Use
try...catchfor proper error handling. - Avoid synchronous APIs inside Express or HTTP servers.
- Always specify
"utf-8"when reading text files. - Keep file operations asynchronous whenever possible.
- Use descriptive file names and validate file paths before performing operations.
Common Beginner Mistakes
Here are some common mistakes developers make:
- Forgetting to handle file operation errors.
- Using synchronous APIs inside API routes.
- Mixing callback and Promise styles in the same function.
- Forgetting to use
awaitwith Promise APIs. - Assuming asynchronous operations execute immediately.
Final Thoughts
Node.js gives developers three different ways to work with the file system, each designed for different scenarios.
In this article, you learned:
- What the File System module is
- How Synchronous APIs work
- How Callback APIs work
- How Promise APIs work
- The differences between the three approaches
- Real-world examples for each style
- Best practices for choosing the right API
While all three approaches are still supported, Promise APIs with async/await have become the preferred choice for modern Node.js development because they combine asynchronous performance with clean and readable code.
Understanding all three styles will help you read existing codebases, maintain legacy applications, and build efficient, production-ready backend systems.
Happy Coding! 🚀