๐ Day 3: Node.js File System (fs) Module โ Reading and Writing Files

Table of contents
- ๐ฏ What Youโll Learn Today:
- ๐ฆ What is the fs Module?
- ๐ Why is the fs Module Useful?
- โ๏ธ 1. Writing to a File (Create or Overwrite)
- ๐ 2. Reading a File
- โ 3. Appending to a File
- โ 4. Deleting a File
- ๐ 5. Creating a Folder (Directory)
- ๐ง Real-Life Example: Saving User Feedback in a File
- ๐งฐ Best Practices for Working Professionals
- ๐ผ Bonus: Using fs.promises with async/await
- ๐ Practice Tasks for You
- โ Summary
- ๐ You now know how to manage files and folders using Node.js like a backend pro!
๐ฏ What Youโll Learn Today:
What is the
fs
module?How to read and write files
Synchronous vs Asynchronous methods
Real-life examples
Best practices for working professionals
๐ฆ What is the fs
Module?
The fs
module (short for File System) is a core module in Node.js.
It helps us create, read, update, and delete files and folders in your computer system โ using JavaScript.
You donโt need to install it. It's built into Node.js. Just use:
const fs = require('fs');
๐ Why is the fs
Module Useful?
๐ Imagine you are:
Creating a blog and want to save blog posts as files.
Making a log system to store user activity.
Reading a config or setting file.
Creating user reports in text format.
These things can easily be done using the fs
module.
โ๏ธ 1. Writing to a File (Create or Overwrite)
โค Synchronous Way
const fs = require('fs');
fs.writeFileSync('data.txt', 'Hello, this is written by Node.js!');
console.log('File written successfully!');
โ
This creates a new file data.txt
or overwrites if already exists.
โค Asynchronous Way (Recommended)
const fs = require('fs');
fs.writeFile('info.txt', 'This is async writing!', (err) => {
if (err) {
console.log('Error writing file:', err);
} else {
console.log('File written successfully (async)!');
}
});
๐ก Async is better in real-world apps because it doesnโt block other operations.
๐ 2. Reading a File
โค Synchronous Way
const data = fs.readFileSync('data.txt', 'utf-8');
console.log('File Content:', data);
โค Asynchronous Way
fs.readFile('info.txt', 'utf-8', (err, data) => {
if (err) {
console.log('Error reading file:', err);
} else {
console.log('File Content:', data);
}
});
๐ก Always use 'utf-8'
to read the content as text. Without it, you'll get a buffer.
โ 3. Appending to a File
fs.appendFileSync('data.txt', '\nThis is a new line added!');
This will add a new line to the existing content of data.txt
.
โ 4. Deleting a File
fs.unlinkSync('info.txt');
console.log('File deleted!');
Be careful while using this. It permanently deletes the file.
๐ 5. Creating a Folder (Directory)
fs.mkdirSync('myFolder');
console.log('Folder created!');
You can now write files into this folder.
๐ง Real-Life Example: Saving User Feedback in a File
Suppose youโre building a backend app for collecting feedback. You want to store feedback in a file.
โค feedback.js
const fs = require('fs');
const name = "Rahul";
const message = "This course is amazing!";
const feedback = `Name: ${name}\nFeedback: ${message}\n-----------------\n`;
fs.appendFile('feedback.txt', feedback, (err) => {
if (err) {
console.log("Couldn't save feedback");
} else {
console.log("Feedback saved successfully!");
}
});
โ
Every time you run this file, a new feedback will be added to feedback.txt
.
๐งฐ Best Practices for Working Professionals
Practice | Why It's Important |
Prefer async methods | Non-blocking code, better performance |
Use try-catch with fs.promises | Modern promise-based error handling |
Organize file logic in utilities | Clean, maintainable project structure |
Log errors properly | Helps in debugging production issues |
๐ผ Bonus: Using fs.promises
with async/await
const fs = require('fs/promises');
async function readMyFile() {
try {
const content = await fs.readFile('data.txt', 'utf-8');
console.log('File:', content);
} catch (err) {
console.log('Error:', err);
}
}
readMyFile();
๐ This is the modern way professionals use fs
in real projects.
๐ Practice Tasks for You
Create a file
bio.txt
and write your name, age, and goal.Append one new line every time you run the file.
Try reading the file and showing output on the console.
Create a folder
logs
, and write logs insidelogs/log.txt
.
โ Summary
Topic | You Learned |
fs Module | Used to handle file operations in Node.js |
Sync vs Async | Sync blocks the code, Async is non-blocking (better for real apps) |
Reading, Writing, Deleting | Basic operations to manage file content |
Real-life Use | Feedback storage, reports, logs, content writing |
Professional Usage | Use fs.promises , async/await, structured folder logic |
๐ You now know how to manage files and folders using Node.js like a backend pro!
โ Frequently Asked Questions (FAQs)
1) We use writeFile()
instead of writeFileSync()
in real projects. Can we use .appendFile()
instead of .appendFileSync()
too?
โ
Yes, absolutely!
Just like writeFileSync()
has an asynchronous version writeFile()
,appendFileSync()
also has an async version called appendFile()
.
Hereโs how you use it:
const fs = require('fs');
fs.appendFile('data.txt', '\nThis is a new async line!', (err) => {
if (err) throw err;
console.log('Line appended asynchronously!');
});
๐ So, always prefer async methods (appendFile
, writeFile
, etc.) in real-world applications to avoid blocking your server.
2) Can we use an async version of unlinkSync()
?
โ
Yes!
The async version is simply: fs.unlink()
Example:
fs.unlink('data.txt', (err) => {
if (err) throw err;
console.log('File deleted asynchronously!');
});
So, in professional apps, prefer:
Sync Method | Async Version |
unlinkSync() | unlink() |
3) Is there an async version of mkdirSync()
?
โ
Yes!
Use fs.mkdir()
instead of fs.mkdirSync()
for asynchronous folder creation.
fs.mkdir('logs', (err) => {
if (err) throw err;
console.log('Folder created asynchronously!');
});
๐ If the folder already exists, it may throw an error. You can pass { recursive: true }
to create nested folders safely:
fs.mkdir('logs/subfolder', { recursive: true }, (err) => {
if (err) throw err;
console.log('Nested folder created!');
});
๐ง Quick Comparison Table
Task | Sync Method | Async Version |
Write file | writeFileSync() | writeFile() |
Append file | appendFileSync() | appendFile() |
Delete file | unlinkSync() | unlink() |
Create folder | mkdirSync() | mkdir() |
Read file | readFileSync() | readFile() |
โ
Recommendation:
Use async versions in all real projects to keep your server fast and non-blocking.
Sync methods can be used for:
Quick scripts
Learning/demo projects
CLI utilities where performance isnโt critical
๐ Stay Connected
If you found this article helpful and want to receive more such beginner-friendly and industry-relevant Node JS notes, tutorials, and project ideas โ ๐ฉ Subscribe to our newsletter by entering your email below.
And if you're someone who wants to prepare for tech interviews while having a little fun and entertainment, ๐ฅ Donโt forget to subscribe to my YouTube channel โ Knowledge Factory 22 โ for regular content on tech concepts, career tips, and coding insights!
Stay curious. Keep building. ๐
Subscribe to my newsletter
Read articles from Payal Porwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Payal Porwal
Payal Porwal
Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: ๐ In-depth explorations of emerging technologies ๐ก Practical tutorials and how-to guides ๐งInsights on software development best practices ๐Reviews of the latest tools and frameworks ๐ก Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Letโs connect and grow together! ๐