๐Ÿงฐ Node.js File & Server Operations
Estimated reading: 3 minutes 417 views

Node.js โ€“ File System Module โ€“ Read, Write, and Manage Files with fs


Introduction โ€“ What Is the File System Module in Node.js?

The File System module (fs) in Node.js allows developers to interact with the file system directly from their applications. You can read, write, delete, rename, and manage files and directoriesโ€”all asynchronously or synchronously.

Whether youโ€™re building a file uploader, a static site generator, or a logging system, the fs module is an essential part of any backend developerโ€™s toolkit.

In this guide, youโ€™ll learn:

  • How to perform basic file and directory operations
  • Use both asynchronous and synchronous APIs
  • Understand file reading/writing, deleting, renaming, and checking
  • Real-world code examples with output

Loading the File System Module

To use the fs module, you must first require it:

const fs = require('fs');

Reading Files โ€“ fs.readFile() (Async) & fs.readFileSync() (Sync)

Asynchronous Read:

fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log('File content:', data);
});

Synchronous Read:

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

Output:

File content: Hello from the file!

Writing Files โ€“ fs.writeFile() & fs.appendFile()

Overwrite File Content:

fs.writeFile('output.txt', 'New Content', (err) => {
  if (err) throw err;
  console.log('File written successfully.');
});

Append to File:

fs.appendFile('output.txt', '\nMore content', (err) => {
  if (err) throw err;
  console.log('Appended successfully.');
});

Result in output.txt:

New Content
More content

Deleting Files โ€“ fs.unlink()

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

Output:

File deleted

Working with Directories

Create a Directory:

fs.mkdir('logs', (err) => {
  if (err) throw err;
  console.log('Directory created');
});

Remove a Directory:

fs.rmdir('logs', (err) => {
  if (err) throw err;
  console.log('Directory removed');
});

Rename or Move a File โ€“ fs.rename()

fs.rename('old.txt', 'new.txt', (err) => {
  if (err) throw err;
  console.log('File renamed');
});

Output:

File renamed

Check If File or Directory Exists โ€“ fs.existsSync()

if (fs.existsSync('new.txt')) {
  console.log('File exists');
}

Output:

File exists

Watch for File Changes โ€“ fs.watchFile()

fs.watchFile('example.txt', () => {
  console.log('File was changed!');
});

Great for logging or real-time sync tools.


Summary โ€“ Recap & Next Steps

The Node.js fs module enables low-level interaction with the file system using both synchronous and asynchronous methods. Itโ€™s vital for backend scripts, CLI tools, log management, and more.

Key Takeaways:

  • Use readFile, writeFile, unlink, mkdir, rename, etc.
  • Prefer asynchronous methods for production use
  • Always include error handling for safe I/O operations

Real-world relevance:
Used in loggers, data importers, file uploaders, static site generators, and system monitors.


FAQs โ€“ Node.js File System Module


What is the difference between fs.readFile() and fs.readFileSync()?
fs.readFile() is asynchronous and non-blocking; fs.readFileSync() blocks execution until the file is read.


How to append content to a file in Node.js?
Use fs.appendFile() for adding new content to an existing file.


Can I check if a file exists without throwing an error?
Use fs.existsSync() to check safely before reading or writing.


How do I delete a directory in Node.js?
Use fs.rmdir() or fs.rm(path, { recursive: true }) in newer versions.


Is it better to use sync or async methods?
Async methods are better for production environments to avoid blocking the event loop.


Share Now :
Share

๐Ÿ“ Node.js โ€“ File System Module

Or Copy Link

CONTENTS
Scroll to Top