Published on

Mastering the fs Module in Node.js — The Easy Way

Authors
react-19-rc-new-hooks-banner

The fs module in Node.js stands for File System, and it's one of the most powerful built-in modules that lets you handle files and folders directly from your code.

In this blog, I’ll break it down with easy explanations and real-life code examples so even beginners can understand. Let’s start step by step.

Basic File Read & Write (Sync vs Async)

Sync Methods (fs.readFileSync, fs.writeFileSync)

  • Blocking: Code stops here until the file operation is complete.
  • Use only for small files.
const fs = require('fs')

// Writing to a file (Sync)
fs.writeFileSync('test.txt', 'Hello Node')
console.log('File written successfully')

// Reading from a file (Sync)
const data = fs.readFileSync('test.txt', 'utf-8')
console.log('File content:', data)

Async Methods (fs.readFile, fs.writeFile)

  • Non-blocking: Code continues to run. Better performance.
  • Use for large files or in production apps.
fs.writeFile('async.txt', 'hello async node', (err) => {
  if (err) throw err
  console.log('Async file written successfully')
})

fs.readFile('async.txt', 'utf-8', (err, data) => {
  if (err) throw err
  console.log('Async file content:', data)
})
Note: Use async with error-first callbacks (err) for safe error handling.

Append & Delete Files

Append Data to File (fs.appendFile)

fs.appendFile('test.txt', '\nThis is new append content by node', (err) => {
  if (err) throw err
  console.log('Appended content successfully')
})
fs.unlink('test.txt', (err) => {
  if (err) throw err
  console.log('File deleted successfully')
})
Tip: Check if file exists before deleting using fs.existsSync("filename").

Working with Folders (Directories)

Create Directory (fs.mkdir)

fs.mkdir('kunwar-dir', { recursive: true }, (err) => {
  if (err) throw err
  console.log('Folder created successfully')
})

Read Directory (fs.readdir)

fs.readdir('kunwar-dir', (err, files) => {
  if (err) throw err
  console.log('Files in the folder:', files)
})

Delete Directory (fs.rmdir)

This is commented "//" to avoid accidental deletion
// fs.rmdir("kunwar-dir", { recursive: true }, (err) => {
//   if (err) throw err;
//   console.log("Folder deleted successfully");
// })

recursive: true allows nested folders to be created or deleted.

Streams — For Large Files

Streams are great when you're handling big files, like videos, logs, or real-time data.

Write Stream

const writeStream = fs.createWriteStream('bigfile.txt')
writeStream.write('This file contains large data\n')
writeStream.write('it is node power\n')
writeStream.end()

writeStream.on('finish', () => {
  console.log('File write completed with stream')
})

Read Stream (Commented Example)

This example reads a file chunk-by-chunk.

// const readStream = fs.createReadStream("async.txt", "utf-8");
// readStream.on("data", (chunk) => {
//   console.log("Chunk read:", chunk);
// });
// readStream.on("end", () => {
//   console.log("File read completed");
// });
// readStream.on("error", (err) => {
//   console.error("Error reading file:", err);
// });

Streams are efficient and used in backend systems for fast processing.

Rename & Move Files

Rename File

fs.rename('async.txt', 'renamed.txt', (err) => {
  if (err) throw err
  console.log('File renamed successfully')
})

Move File

fs.rename('renamed.txt', 'kunwar-dir/moved.txt', (err) => {
  if (err) throw err
  console.log('File moved successfully')
})

Just pass a new path in fs.rename() to move files easily.

Watch File Changes (Real-time Monitoring)

Want to track live changes in a file (like logs or config updates)? Use fs.watch.

fs.watch('bigfile.txt', (eventType, filename) => {
  console.log(`Event type: ${eventType}`)
  console.log(`File name from watch: ${filename}`)
})

Every time the file is modified, this will run automatically.

Quick Summary Table

FunctionSyncAsyncDescription
fs.readFileSync✅❌Read file (blocking)
fs.readFile❌✅Read file (non-blocking)
fs.writeFileSync✅❌Write file (blocking)
fs.writeFile❌✅Write file (non-blocking)
fs.appendFile❌✅Append content to file
fs.unlink❌✅Delete file
fs.mkdir❌✅Create folder
fs.readdir❌✅Read folder contents
fs.rmdir❌✅Delete folder
fs.createReadStream✅✅Read large file with chunks
fs.createWriteStream✅✅Write large file with chunks
fs.watch❌✅Watch for file changes in real time

Final Thoughts

Node.js’s fs module is like a Swiss army knife for handling files and folders. Whether you're building a logging system, a file uploader, or a backend dashboard — mastering this module will give you a big boost.

Use sync methods for small tasks, and async or streams for real-time and production apps.

Share this post