๐Ÿงฐ Node.js File & Server Operations
Estimated reading: 3 minutes 19 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

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

Or Copy Link

CONTENTS
Scroll to Top