What is File System Module in Node.js ?
Last Updated :
10 Jul, 2024
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:
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.
Similar Reads
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 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 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
What is the scope of require module in Node.js ?
Whenever we have to use any feature of any other module shared by "module.exports" in our Node.js application, then we use require() method. That means we are importing those shared features into our own module and after that, we can use those features. Now the biggest question is -what is the scope
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 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 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
What is package.json in Node.js ?
In the world of Node.js development, package.json is a crucial file that serves as the heart of any Node.js project. It acts as a manifest that defines the projectâs metadata, dependencies, scripts, and more. This article will provide an in-depth look at what package.json is, why it's essential, and
4 min read