For enquiries call:

Phone

+1-469-442-0620

HomeBlogWeb DevelopmentHow to Install & Use FS Module in Node JS? Step-by-Step Guide

How to Install & Use FS Module in Node JS? Step-by-Step Guide

Published
29th Apr, 2024
Views
view count loader
Read it in
10 Mins
In this article
    How to Install & Use FS Module in Node JS? Step-by-Step Guide

    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. If you are a beginner and want more information, then you can go for Full Stack Developer training.   

    Node Module fs: An Overview

    Node.js has a wide range of modules for various purposes and to ease your development task. One of those useful modules is the nodejs install “fs” module. The fs module helps you to work around the files and directories to carry out different tasks, such as a store, access, read, write, rename, and others.

    There is no need to install fs in node js to use it. In this Node.js master class, you will learn the following.

    • What is the basic usage of the fs (file system) module?
    • Prerequisites to install fs module in node js
    • Asynchronous and synchronous fs methods?
    • How to install and use the fs module in node.js
    • How to read from the file using fs.read?
    • How to write to file using fs.write?
    • How to delete a file (new or existing) using fs.unlink?
    • How to rename a file using fs.rename?
    • How to create and delete a system directory in Node.js?
    • When you should not use the Node.js fs module?

    Prerequisites to Install NPM FS Module in Node JS

    To get started with your Node.js, first install the latest version on your system. You can even join the knowledgeHut Node.js master class to get more information about working with Node.js in detail. If you have Node.js, you can start with the coding part. But, before that, we will learn about asynchronous and synchronous fs methods.

    Asynchronous vs Synchronous fs Methods

    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
    • fs.readFile()
    • fs.rename()
    • fs.write()
    • fs.writeFile()
    • fs.fsync()
    Synchronous methods of fs module in NodeJS:
    • fs.readFileSync()
    • fs.writeFileSync()
    • fs.fsyncSync()
    • fs.appendFileSync()
    • fs.statSync()

    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.

    How to Install and Use the fs Module in Node JS?

    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.  

    Reading Files Using fs.readFile()

    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. For a deeper understanding on web development, enroll in a Web Developer Course online.  

    • To get started, we will create a folder, named “hello”. Go to the desktop and create the folder named “hello”. We will be using this folder for further coding.
    • We are using the VS Code to run the Node.js. So, install its latest version and open the application on your system. The screen looks this.

    • Click on the open folder option on the top and navigate to your desktop's “hello” folder. Now go to the “Run and Debug” the fourth option on the left-side pane as shown in the above image. You will get the terminal, where you can run further commands.

    • Then change the working directory to the above-mentioned newly created directory, hello. Run the following command to do so.
    cd hello

    • Now, we will create a file in this “hello” folder. We will try to read its content. To create a new file “file1.txt”, we will click the new file option as shown below.

    Enter the “this is the first file to get the content” on the right-side pane and save the file.

    • Create another file under the “hello” folder. This file will contain the code to read the content of the “file1.txt”. We will name this file “findContent.js”. To create the file, we will follow the above same process.

    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. 

    1. As you can see, we have used the promise version of the fs module. The promises object in the fs module uses promises so the fs module continues to expose callback functions.
    2. Then, we create the async function (using the async keyword) to read the file’s content. The async function resolves the promises using the await keyword. Mention the readFile() function by taking the file path as an argument. Then the try..catch block will handle the unexpected error. In this case, the error could be due to the missing file or the code does not have the required access to get the file’s content.
    3. Then, we have to mention the file name “file1.txt” that we have created with content.
    • To run the “findContent.js” file, you need to hit the following command on the terminal.
    node findContent.js 

    Writing Files Using fs.writeFile()

    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.

    • In this code, we will create two different functions where the first will create the CSV file and another one will add the data. Open the writeContent.js file and add the following code.
    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. 

    1. First, we will import the fs module, the promise version. 
    2. Here, with the async function we are creating a variable “csvHeaders” storing the headers of the CSV file. Then the writeFile() function will create a file in the current working directory and add content to it.
    3. With this second function “addGadget”, we will be adding items to your gadget list. The writeFile() method has a third argument: a JavaScript object (a) specifying the append operation.
    4. To call the addGadget function, we have created a wrapper function with an async function. You have to wrap the asynchronous functions in an async function as openFile() and addGadget() are asynchronous functions. If you do not enclose them, it will disrupt the order of the call.

    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.

    • To list the content, we have run the following command.
    cat gadgets.csv

    Deleting Files Using fs.unlink()

    To delete a file, the fs module provides the unlink() method of the fs module. Here, we will delete the gadgets.csv file.

    • First, we will create a file “deleteContent.js” that will store the code to 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. 

    1. We have imported the fs module to use the unlink method. 
    2. Then we use an async deleteFile() function where we specify the file path as an argument. Then we are passing the filepath to the unlink() function (with one argument- file path to delete the file) that will remove the file from your filesystem. 
    3. At last, we have passed the “gadgets.csv” file to the deleteFile function. 
    • Now, run the “deleteContent.js” using the following command. 
    node deleteContent.js 

    • To confirm the deletion, we will check the contents of the hello folder.

    Renaming Files Using fs.rename()

    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.

    • Use the following command to create a new directory in cwd.
    mkdir hello_1

    You can see the folder “hello_1” on the left-side pane. 

    • Now we will create a “renameContent.js” file with the following code.
    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.

    1. We have imported the fs module with a promise version. To use the rename function. 
    2. Then we have created an async function called moveFile() to call the rename() function. The rename() function will take two parameters- source and destination to copy the file. Where the source specifies the original file and the destination specifies the path of the destination location.
    3. Then comes the moveFile function where we have passed the parameters to copy the file. 
    • Now run the js file to complete the process. 
    node renameContent.js 

    • Confirm the copying of the file using the following command.

    Create and Delete a Directory

    A. Creating directory

    The fs module provides the mkdir() method to create a new directory.

    • Create a new file “newDir.js” under the cwd with the following code. 
    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. 

    1. We have imported the fs module to use the mkdir function for creating a new directory. 
    2. We have used the mkdir function and have passed different arguments. The first argument will create the directory under the cwd (current working directory) using the process object. Then we passed the folder name (you can mention a different path also). The second parameter is the recursive option. If it is not set to true, you cannot create multiple folders. 
    • To run the code for “newDir.js”, run the following command from the VS terminal, as shown below. 
    node newDir.js

    Also, we have confirmed the creation of a new directory using the “ls hello” command. 

    B. Deleting directory

    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. 

    • We will create a new file “delDir.js” with the following code. 
    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!'); 
    }); 
    • We have imported the fs module to use the rmdir function to delete the directory. Again, we have passed the path to the same directory path with the recursive option set to true. 
    • Now we will run the “delDir.js” file using the following command. 
    Node delDir.js 
    • To confirm the deletion, we have run the following command. 
    cd hello 

    Looking to level up your coding skills? Join our advanced Python course and unlock endless possibilities. From data analysis to machine learning, become a Python pro in no time. Don't miss out, enroll today!

    Conclusion

    Node.js comes with powerful modules. One of them is an fs module. 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.

    If you are interested in exploring Node.js in-depth, we encourage you to sign up for KnowledgeHut’s Node.js and upskill yourself. 

    Frequently Asked Questions (FAQs)

    1What is the Node fs module?
    This module is for handling the file system, as fs stands for the file system. There is no need to install this module, as it is available as a built-in module that comes with the installation of Node.js.
    2How to install fs in Node.js?

    There is no need to explicitly use “npm install fs” to install the fs module. It is a built-in module that comes with the node.js installation. You only have to import it into the code using the “require” function. 

    3How can I work with files using module fs in Node.js?

    You can write to, read from, append, rename, delete, unlink, and perform various other tasks with your file. Without importing the fs module in your code, you cannot access different functions of the fs module.

    4Which module fs method is required to write a file?

    The fs module provides the fs.writeFile() function to write the content to the file. If the mentioned file does not exist, it will create a new file. Else, in the case of the existing file, it will append the data to the file. Below is the syntax. 

    fs.writeFile('filename',{ flag: 'a' }); 

    The flag “a” tells that you are appending to the file. 

    5Where does NPM install its modules?

    By default, the modules are installed under the node_modules subfolder.

    Profile

    Aashiya Mittal

    Author

    Aashiya has worked as a freelancer for multiple online platforms and clients across the globe. She has almost 4 years of experience in content creation and is known to deliver quality content. She is versed in SEO and relies heavily on her research capabilities.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon