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

Payal PorwalPayal Porwal
6 min read

๐ŸŽฏ 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.


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

PracticeWhy It's Important
Prefer async methodsNon-blocking code, better performance
Use try-catch with fs.promisesModern promise-based error handling
Organize file logic in utilitiesClean, maintainable project structure
Log errors properlyHelps 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

  1. Create a file bio.txt and write your name, age, and goal.

  2. Append one new line every time you run the file.

  3. Try reading the file and showing output on the console.

  4. Create a folder logs, and write logs inside logs/log.txt.


โœ… Summary

TopicYou Learned
fs ModuleUsed to handle file operations in Node.js
Sync vs AsyncSync blocks the code, Async is non-blocking (better for real apps)
Reading, Writing, DeletingBasic operations to manage file content
Real-life UseFeedback storage, reports, logs, content writing
Professional UsageUse 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 MethodAsync 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

TaskSync MethodAsync Version
Write filewriteFileSync()writeFile()
Append fileappendFileSync()appendFile()
Delete fileunlinkSync()unlink()
Create foldermkdirSync()mkdir()
Read filereadFileSync()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. ๐Ÿš€

0
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! ๐ŸŒŸ