Working with File System - Using the fs module in Node.js to Read and Write Files

Renil GaralaRenil Garala
3 min read

Have you ever wondered how your computer stores all your documents, music, and code files? What if your program could read those files, create new ones, or even delete them — just like you do manually?

Imagine you're building a text editor, a blog, or even a log system — all these applications need to interact with the file system. In Node.js, this is not only possible but also very simple, thanks to the powerful built-in module called fs (short for File System).

In this article, we’ll explore how to read and write files in Node.js using the fs module. By the end, you'll be able to create and manipulate files just like a pro!


🔧 What is the fs Module?

Node.js comes with a built-in module called fs that allows you to work with files and directories. You don’t need to install it, just require it in your code, and you're good to go!

The fs module provides both:

  • Synchronous methods (Blocking)

  • Asynchronous methods (Non-blocking - better for performance)


🛠️ Getting Started

Let’s first include the fs module:

const fs = require('fs');

📖 1. Reading Files

🔹 Asynchronous Method (Non-blocking)

fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading the file:', err);
    return;
  }
  console.log('File content:', data);
});

Breakdown:

  • 'example.txt': name of the file you want to read

  • 'utf8': encoding (so you get readable text)

  • err: error if something goes wrong

  • data: the actual file content

🔹 Synchronous Method (Blocking)

const data = fs.readFileSync('example.txt', 'utf8');
console.log('File content:', data);

Use this only when you're okay with blocking the execution (e.g., scripts or tools).


📝 2. Writing to Files

🔹 Asynchronous Method

fs.writeFile('output.txt', 'Hello, Node.js!', (err) => {
  if (err) {
    console.error('Error writing to the file:', err);
    return;
  }
  console.log('File has been written successfully!');
});
  • If output.txt doesn’t exist, it will be created.

  • If it exists, its content will be overwritten.

🔹 Synchronous Method

fs.writeFileSync('output.txt', 'Hello again!');
console.log('Written using writeFileSync');

➕ 3. Appending to Files

You can add content instead of replacing it using:

fs.appendFile('output.txt', 'Adding more text...', (err) => {
  if (err) throw err;
  console.log('Content appended!');
});

❌ 4. Deleting Files

Want to remove a file?

fs.unlink('output.txt', (err) => {
  if (err) throw err;
  console.log('File deleted!');
});

Be careful with this — there's no going back!


📂 5. Working with Directories

Create a new folder:

fs.mkdir('newFolder', (err) => {
  if (err) throw err;
  console.log('Folder created!');
});

Read contents of a folder:

fs.readdir('./', (err, files) => {
  if (err) throw err;
  console.log('Files in directory:', files);
});

Delete a folder:

fs.rmdir('newFolder', (err) => {
  if (err) throw err;
  console.log('Folder deleted!');
});

🧠 Why Use Asynchronous Methods?

Asynchronous methods are non-blocking - meaning your program continues running while the file is being read or written. This is very important for performance, especially in web servers or large applications.


✅ Final Thoughts

Working with the file system in Node.js opens up endless possibilities. Whether you're storing user data, creating log files, or building a file manager, the fs module is your go-to tool.

And the best part? You don’t need any external library, it’s all built into Node.js!


If you want the code files used in this article, or a demo project using fs, let me know, I’d be happy to help!

10
Subscribe to my newsletter

Read articles from Renil Garala directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Renil Garala
Renil Garala

A 20-year-old web developer, certified in Java. Pursuing a BCA in the third year and currently learning full-stack web development from Chaicode.