Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
What are Modules in Node.js ?
Next article icon

What is File System Module in Node.js ?

Last Updated : 10 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Node.js is a powerful platform for building server-side applications, and one of its key features is its ability to interact with the file system. The File System (fs) module in Node.js provides an extensive API to work with files and directories, allowing developers to perform operations such as reading, writing, updating, and deleting files and directories. This article provides a comprehensive overview of the fs module, its features, and how to use it effectively in your applications.

File System (fs) Module in Node

The File System module, abbreviated as fs, is a core module in Node.js that allows you to interact with the file system in a way modeled on standard POSIX functions. It provides both synchronous and asynchronous methods for various file operations. The asynchronous methods are non-blocking, which means the file operations are executed in the background, allowing the application to continue running other tasks.

Key Features of the fs Module

  • File Reading and Writing: Easily read from and write to files, supporting both text and binary data.
  • File Manipulation: Create, delete, rename, and move files and directories.
  • File Statistics: Retrieve detailed information about files, such as size, creation date, and permissions.
  • Stream Handling: Efficiently handle large files and data streams.

Importing the fs Module

To use the fs module in your Node.js application, you first need to import it using the require function:

const fs = require('fs');

Common Operations with the fs Module

The basic operations performed using the fs module are:

Table of Content

  • Reading Files
  • Writing Files
  • Appending to Files
  • Reading Directory Contents

Reading Files

Asynchronous Reading

Use fs.readFile to read the contents of a file asynchronously. The function takes the file path, encoding, and a callback function to handle the result.

const fs = require('fs');

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

Synchronous Reading

Use fs.readFileSync for synchronous file reading. This method blocks the execution until the file is completely read.

const fs = require('fs');

try {
const data = fs.readFileSync('example.txt', 'utf8');
console.log('File content:', data);
} catch (err) {
console.error('Error reading file:', err);
}

Writing Files

Asynchronous Writing

Use fs.writeFile to write data to a file asynchronously. If the file does not exist, it will be created.

const fs = require('fs');

const content = 'Hello, Node.js!';

fs.writeFile('example.txt', content, 'utf8', (err) => {
if (err) {
console.error('Error writing file:', err);
return;
}
console.log('File written successfully!');
});

Synchronous Writing

Use fs.writeFileSync to write data to a file synchronously.

const fs = require('fs');

const content = 'Hello, Node.js!';

try {
fs.writeFileSync('example.txt', content, 'utf8');
console.log('File written successfully!');
} catch (err) {
console.error('Error writing file:', err);
}

Appending to Files

Asynchronous Appending

Use fs.appendFile to add data to the end of a file asynchronously.

const fs = require('fs');

const additionalContent = '\nAppended content.';

fs.appendFile('example.txt', additionalContent, 'utf8', (err) => {
if (err) {
console.error('Error appending to file:', err);
return;
}
console.log('Content appended successfully!');
});

Synchronous Appending

Use fs.appendFileSync to append data to a file synchronously.

const fs = require('fs');

const additionalContent = '\nAppended content.';

try {
fs.appendFileSync('example.txt', additionalContent, 'utf8');
console.log('Content appended successfully!');
} catch (err) {
console.error('Error appending to file:', err);
}

Reading Directory Contents

Asynchronous Directory Reading

Use fs.readdir to read the contents of a directory asynchronously.

const fs = require('fs');

fs.readdir('new_directory', (err, files) => {
if (err) {
console.error('Error reading directory:', err);
return;
}
console.log('Directory contents:', files);
});

Synchronous Directory Reading

Use fs.readdirSync to read the contents of a directory synchronously.

const fs = require('fs');

try {
const files = fs.readdirSync('new_directory');
console.log('Directory contents:', files);
} catch (err) {
console.error('Error reading directory:', err);
}

Conclusion

The File System module in Node.js provides a comprehensive API for working with the file system. Whether you need to read, write, manipulate files, or get detailed information about them, the fs module has you covered. It supports both synchronous and asynchronous operations, allowing you to choose the best method for your application based on performance and complexity needs.



Next Article
What are Modules in Node.js ?

D

divyambhutani40
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Node.js-fs-module
  • NodeJS-Questions

Similar Reads

  • What are Modules in Node.js ?
    In Node.js Application, a Module can be considered as a block of code that provide a simple or complex functionality that can communicate with external application. Modules can be organized in a single file or a collection of multiple files/folders. Almost all programmers prefer modules because of t
    5 min read
  • What are modules in Node JS ?
    In NodeJS, modules are encapsulated units of code that can be reused across different parts of an application. Modules help organize code into smaller, manageable pieces, promote code reusability, and facilitate better maintainability and scalability of NodeJS applications. Types of Modules:Core Mod
    2 min read
  • What is the purpose of module.exports in node.js ?
    The module.exports is actually a property of the module object in node.js. module. Exports is the object that is returned to the require() call. By module.exports, we can export functions, objects, and their references from one file and can use them in other files by importing them by require() meth
    3 min read
  • Node.js File System
    The fs (File System) module in Node.js provides an API for interacting with the file system. It allows you to perform operations such as reading, writing, updating, and deleting files and directories, which are essential for server-side applications and scripts. Table of Content Node.js file systemK
    9 min read
  • What is Buffer in Node.js ?
    In Node, Buffer is used to store and manage binary data. Pure JavaScript is great with Unicode-encoded strings, but it does not handle binary data very well. It is not problematic when we perform an operation on data at the browser level but at the time of dealing with TCP stream and performing a re
    3 min read
  • What is Crypto Module in Node.js and How it is used ?
    The crypto module in Node.js provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. This module enables you to perform various security operations, such as hashing, encryption, and decryption, directly in your Node
    4 min read
  • What is spawn in Node JS ?
    Node JS is a cross-platform, open-source back-end JavaScript runtime environment that uses the V8 engine to execute JavaScript code outside of an internet browser. In this article, we will learn about the Spawn in NodeJs. PrerequisitesNodeJS fundamentalsAsynchronous ProgrammingChild ProcessesSpawn i
    3 min read
  • How to install modules without npm in node.js ?
    We can install modules required for a particular project in node.js without npm, the recommended node package manager using yarn. Yarn is a wonderful package manager. Like npm, if you have a project folder with package.json containing all the required dependencies mentioned for the project, you can
    3 min read
  • How to Access the File System in Node.js ?
    In this article, we looked at how to access the file system in NodeJS and how to perform some useful operations on files. Prerequisite: Basic knowledge of ES6Basic knowledge of NodeJS NodeJS is one of the most popular server-side programming frameworks running on the JavaScript V8 engine, which uses
    3 min read
  • What is the purpose of the 'node_modules' folder ?
    The node_modules folder is a directory in NodeJS projects that stores third-party libraries and dependencies. It's essential for managing dependencies, which are packages or modules that a NodeJS project relies on. When you install a package using npm or Yarn, these tools download the package along
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences