Kunwar-Pratap
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.readFileSyncRead file (blocking)
fs.readFileRead file (non-blocking)
fs.writeFileSyncWrite file (blocking)
fs.writeFileWrite file (non-blocking)
fs.appendFileAppend content to file
fs.unlinkDelete file
fs.mkdirCreate folder
fs.readdirRead folder contents
fs.rmdirDelete folder
fs.createReadStreamRead large file with chunks
fs.createWriteStreamWrite large file with chunks
fs.watchWatch 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

Loading reactions...