How to Install FS Module in Node JS? [Step-by-Step Guide]
Updated on Mar 07, 2025 | 22 min read | 24.3k views
Share:
For working professionals
For fresh graduates
More
Updated on Mar 07, 2025 | 22 min read | 24.3k views
Share:
Table of Contents
Node.js is one of the commonly preferred JavaScript runtime server environments, allowing them to create dynamic websites. It is evident that any project can not proceed without having different files holding the code. If any of the files malfunctions, it can impact the entire project. Working and managing files is crucial, but with Node.js you can do it efficiently. Not just handling, you can easily read, write, rename, or delete a file and save time for every developer.
Node.js lets the developers alter the files with its built-in fs (file system) module. The node js fs install module comes with all basic functions that you can perform for a specific file within your project. So, let's dive into the information on how to install fs module in Node.js.
Before diving into the installation steps, let's shed light on what the NPM fs module in node js entails. In the vast ecosystem of Node.js, the NPM (Node Package Manager) `fs` module stands as a cornerstone for developers seeking to engage with the intricacies of file system operations. "NPM FS" refers to the Node.js core module known as File System, providing a versatile set of functions that empower developers to interact with files and directories seamlessly. As an experienced Node.js enthusiast, I can attest to the fundamental role the fs module in node js plays in shaping robust applications.
Imagine `fs` as a toolkit within Node.js, equipped with tools for reading, writing, and manipulating files. Its capabilities extend to handling directories, making it an indispensable asset for a myriad of applications, from web servers managing file uploads to scripts automating file-related tasks.
This module operates synchronously and asynchronously, allowing developers to choose the method that best suits the needs of their applications. Whether you're building a file explorer, a content management system, or a data processing pipeline, the fs module in node js serves as your trusty companion, offering a rich set of functions to navigate the intricacies of file management in a Node.js environment. Throughout this guide, we'll explore how to harness the power of NPM FS, unlocking new dimensions in Node.js development.
Apply to upGrad’s Full Stack Software Development Bootcamp to acquire job-ready software skills and learn how to develop a web application’s backend using the fs module in Node.js.
Source: cloudinary
Embarking on the journey of Node.js development begins with the essential step of installing the Node.js runtime on your machine. This step-by-step guide will walk you through the process, ensuring a seamless setup for unleashing the power of Node.js and its versatile ecosystem of modules.
Following these steps ensures that Node.js is installed on your system, laying the foundation for exploring its rich ecosystem of modules. With Node.js in place, you're now ready to delve into the next steps of installing the `fs` module and unlocking the potential of file system operations in your Node.js projects.
The fs modules let you seamlessly work and manage the files and directories in your system. All you need is to include it in your code using the “require” function and passing fs as the parameter, as shown below.
const fs = require('fs');
After using the above code, you can get access to the several methods that are mentioned below.
Method | Description |
fs.access() | check the existence of the file and access it with its permission. |
fs.chmod() | it lets you change the permission for the file. |
fs.chown() | lets you change the owner and group of the file. |
fs.close() | closes the file descriptor. |
fs.copyFile() | it will copy the file. |
fs.link() | it will create a new hard link for the specified file. |
fs.mkdir() | You can create a new directory. |
fs.mkdtemp() | it will create a new temp directory. |
fs.open() | It will open the file to make the changes. |
fs.readdir() | You can read the directory’s content. |
fs.readFile() | read the file’s content. |
fs.readlink() | You can read the symbolic link’s content. |
fs.realpath() | It will resolve the relative path for you. |
fs.rename() | It lets you rename the file or directory name. |
fs.rmdir() | It lets you remove the directory. |
fs.stat() | It will return the mentioned file’s stats. |
fs.symlink() | You can create a new symbolic link. |
fs.truncate() | It will truncate the file’s length as mentioned. |
fs.unlink() | It will remove the symbolic link. |
fs.unwatchFile() | It will ignore the changes made to a specific file. |
fs.utimes() | It lets you change the file’s timestamp. |
First, to read the content from the file, we will import the fs module in the code. It lets you access the readFile() method. We will explain the working of how fs.readFile() works, we will be considering the following example.
cd hello
Enter the “this is the first file to get the content” on the right-side pane and save the file.
You can see the file under the hello folder.
Now add the following code on the right side pane and save it (ctrl + s).
const fs = require('fs').promises; //1
async function readFile(filePath) { //2
try {
const data = await fs.readFile(filePath);
console.log(data.toString());
} catch (error) {
console.error(`Got an error trying to read the file: ${error.message}`);
}
}
readFile('file1.txt'); //3
You can see that we marked the above code as 1,2, and 3. It is important to understand why we used this code and how it will get the file1.txt’s content.
You can see that we marked the above code as 1,2, and 3. It is important to understand why we used this code and how it will get the file1.txt’s content.
node findContent.js
Check out our free technology courses to get an edge over the competition.
The fs module lets you write the content to the file. For example, we are creating a CSV file storing information about gadgets. With the first command, it will create the file. Then, with the next command, we will append the content to the created file. We will create a new file “writecontent.js” as we had created the earlier file.
const fs = require('fs').promises; //1
async function openFile() { //2
try {
const csvHeaders = 'name,price'
await fs.writeFile('gadgets.csv', csvHeaders);
} catch (error) {
console.error(`Got an error trying to write to a file: ${error.message}`);
}
}
async function addGadget(name, price) { //3
try {
const csvLine = `\n${name},${price}`
await fs.writeFile('gadgets.csv', csvLine, { flag: 'a' });
} catch (error) {
console.error(`Got an error trying to write to a file: ${error.message}`);
}
}
(async function () { //4
await openFile();
await addGadget('laptop’, 23000);
await addGadget(‘mobile’, 12000);
})();
Let’s see, what the above code is doing. Again, we have marked the code.
Run the writeContent.js file using the following command from the VS terminal.
node writeContent.js
As you can see the gadgets.csv file has been created under the hello folder.
cat gadgets.csv
Apply to the Master of Science in Computer Science from LJMU to learn full stack development master using Node fs modules.
To delete a file, the fs module provides the unlink() method of the fs module. Here, we will delete the gadgets.csv file.
const fs = require('fs').promises; //1
async function deleteFile(filePath) { //2
try {
await fs.unlink(filePath);
console.log(`Deleted ${filePath}`);
} catch (error) {
console.error(`Got an error trying to delete the file: ${error.message}`);
}
}
deleteFile('gadgets.csv'); //3
Now, we will see what the above code is doing. Again, we have marked different sections of the code.
node deleteContent.js
For moving the files from one location to another, you can use the fs’s rename function. For this, we use the rename() method of the fs module. As we have deleted the gadgets.csv, we are left with file1.txt. We will be copying it to another folder. But first, we will create a destination folder where we will copy it.
mkdir hello_1
You can see the folder “hello_1” on the left-side pane.
const fs = require('fs').promises; //1
async function moveFile(source, destination) { //2
try {
await fs.rename(source, destination);
console.log(`Moved file from ${source} to ${destination}`);
} catch (error) {
console.error(`Got an error trying to move the file: ${error.message}`);
}
}
moveFile('hello/file1.txt', 'hello_1/file2.txt'); //3
We will see what the above code is doing and have marked the sections of the code.
node renameContent.js
The fs module provides the mkdir() method to create a new directory.
const fs = require('fs').promises; //1
fs.mkdir(`${process.cwd()}/hello/data`, { recursive: true }, (err) => { //2
if (err) throw err;
console.log('Folder created successfully!');
});
Now, we will see what the above code is doing.
node newDir.js
Also, we have confirmed the creation of a new directory using the “ls hello” command.
The process will be the same as creating the new directory. All you need is to change the mkdir function with the rmdir function. It is also available under the fs module to delete the directory.
const fs = require('fs').promises; //1
fs.rmdir(`${process.cwd()}/hello/data`, { recursive: true }, (err) => { //2
if (err) throw err;
console.log('Folder deleted successfully!');
});
Node delDir.js
cd hello
In the realm of software development, encountering occasional installation hiccups is not uncommon. Let me share a personal experience that sheds light on navigating these challenges.
Personal Story: Navigating Installation Hiccups
In the midst of a complex project, I found myself grappling with unexpected errors during the installation of the fs module in node.js. The root cause of the issue is traced back to conflicting versions of Node.js and NPM. By strategically downgrading NPM to a version compatible with the project's requirements, I successfully resolved the problem. This experience underscored the critical importance of meticulous version management and troubleshooting skills when tackling installation hurdles.
1. Overcoming Common Hurdles
While installation errors can be a source of frustration, equipping yourself with effective troubleshooting tips can turn these challenges into opportunities for learning and improvement. Here are some common issues and their corresponding solutions:
Incorrect Node.js Version
Ensure that your Node.js version aligns with the requirements of the `fs` module. Consult the module's documentation to identify the recommended Node.js version and update your Node.js accordingly.
npm install -g n
n latest
2. Permissions Issue
If encountering permission-related obstacles during installation, steer clear of using `sudo` with NPM commands. Instead, configure NPM to install global packages without elevated permissions.
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
export PATH=~/.npm-global/bin:$PATH
3. Firewall Restrictions
Firewall restrictions may impede NPM from fetching packages. To address this, adjust your firewall settings to grant NPM unrestricted access to the registry.
4. Proxy Settings
For those operating behind a proxy, configure NPM to align with your proxy settings.
npm config set proxy http://proxy.example.com:8080
npm config set https-proxy http://proxy.example.com:8080
By navigating these troubleshooting tips, you empower yourself to overcome installation challenges effectively and ensure a smooth integration of the `fs` module into your Node.js projects.
While the fs module in Node js is a powerful tool for file system operations, there may be scenarios where uninstallation becomes necessary. Whether project requirements shift, or compatibility issues arise, removing the fs module provides a clean slate for adjustments. Uninstalling the fs module is a straightforward process that ensures your Node.js environment reflects the evolving needs of your project.
Uninstalling the fs module in node js is not a declaration of its inadequacy; rather, it's a strategic decision tailored to the dynamic nature of software development. As you navigate your Node.js projects, the flexibility to install and uninstall modules ensures that your applications remain agile and adaptable to changing circumstances.
Assessing the Need for Uninstallation
Uninstalling the fs module node js becomes a strategic choice in specific scenarios, warranting careful consideration. One compelling reason to uninstall is the evolution of project requirements. As your project's scope shifts, the need for certain modules may diminish, making uninstallation a proactive step in streamlining your project's dependencies.
Additionally, compatibility issues with other modules may prompt the decision to remove the fs module in node js. Ensuring harmonious interactions between various components of your project is pivotal for its overall stability and functionality. Uninstallation provides a clean slate, allowing you to reassess your project's needs and make informed decisions about the inclusion or exclusion of specific modules.
Executing a Clean Uninstallation
To initiate the uninstallation process for the fs module node.js, navigate to your project directory and execute the following command:
npm uninstall fs
This command serves as a straightforward directive to the Node Package Manager (NPM), prompting the removal of the fs module in node js from your project's dependencies. By executing a clean uninstallation, you not only declutter your project but also pave the way for adjusting and optimizing your dependencies based on the evolving dynamics of your development journey.
Before we explore the advantages bestowed by the fs module nodejs, it's crucial to appreciate the transformative power it brings to Node.js development. The fs module, as an integral part of Node.js, opens doors to a realm of possibilities in handling file system operations. Its installation marks not just the inclusion of a module but the infusion of versatility into your applications, enhancing your ability to navigate, manipulate, and interact with files and directories seamlessly.
1. Asynchronous File Operations
The prowess of the fs module in node js shines in its capability to execute asynchronous file operations efficiently. Asynchronous operations, a hallmark of Node.js, enable non-blocking I/O tasks, empowering your applications to handle multiple operations concurrently. This translates to improved performance and responsiveness, particularly crucial in scenarios where tasks like reading, writing, or processing files occur simultaneously.
2. Broad Range of Functions
Dive into a rich repository of functions within the fs module in node js, covering an extensive spectrum of file system operations. Whether your application demands reading the content of a file, writing data to a new file, or manipulating directories, the fs module node js provides dedicated functions tailored to each operation. This versatility simplifies the implementation of diverse file-related tasks, fostering efficiency and code maintainability.
3. Error Handling Capabilities
The robustness of the fs module node js extends to its comprehensive error handling capabilities. Built-in mechanisms ensure that your applications gracefully manage unexpected issues during file operations. Whether it's a missing file, permission-related concerns, or other potential errors, the fs module in node js equips you with tools to handle these scenarios gracefully, enhancing the overall reliability and resilience of your file-centric workflows.
4. Stream-Based Operations
Unlock the efficiency of stream-based operations with the fs module node js. Streams enable the processing of data in manageable chunks, minimizing memory usage and optimizing performance. This feature is particularly valuable when dealing with large files or streaming data between different processes. By leveraging streams, you enhance the efficiency of your file operations and ensure optimal resource utilization within your Node.js applications.
5. Cross-Platform Compatibility
Designed with cross-platform compatibility in mind, the fs module in node js facilitates seamless interaction with the file system across various operating systems. Whether your application runs on Windows, macOS, or Linux, the fs module node js ensures consistent and reliable file system interactions. This cross-platform adaptability streamlines development and deployment processes, allowing your Node.js applications to maintain consistent functionality regardless of the underlying operating system.
The fs module supports the asynchronous and callback-based functions by default. But, not all the functions are asynchronous, some of the functions are synchronous, such as readFileSync and writeFileSync. To avoid the blocking situation and unresponsive application, the I/O operations are also done asynchronously.
It is recommended that all file-related and I/O-related operations must be done asynchronously to avoid the vagueness of your code. So, you must also go for the asynchronous versions of the fs methods while working with the filesystem. But, in some scenarios where you want to explicitly block your program’s execution, you can go for the synchronous versions. Some of those scenarios load configs before the actual program runs.
Asynchronous Methods |
Synchronous Methods |
Non-blocking functions are referred to as synchronous functions. | Blocking functions are referred to as synchronous functions. |
These functions take a callback function as the last argument. | These functions take File Descriptor as the last argument. |
It does not block the execution of the program. | It halts the program's execution until the file operation completes processing. |
Asynchronous methods of fs module in NodeJS
|
Synchronous methods of fs module in NodeJS:
|
For example:
const fs = require("fs");
const config = JSON.parse(fs.readFileSync("./config.json"));
// include your code now.
If you do not want to implement the above scenario, you must use the asynchronous fs method to deal with the file system.
If you do not want to implement the above scenario, you must use the asynchronous fs method to deal with the file system.
By this point, you must developed a better idea of how you can install fs module in Node.js. With this module, you can efficiently play around with the entire filesystem. We have mentioned a list of actions that you can perform using the fs module, its functions and how to install fs module in node js. But, we have explained only the most commonly used functions. If you understand these, you can work with the other functions easily.
One simply needs the fs module in the Node.js script to access its file system capabilities. Register for upGrad’s Executive Post Graduate Programme in Data Science from IIIT Bangalore to hone your knowledge and practical skills in data science.
Boost your software engineering skills with our top programs. Explore the courses below to find the right fit
Master in-demand software skills with our specialized courses. Explore your options below to upskill today
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources