Skip to main content

The File System (FS) module in Node.js

 

Hello my lovely audience on the internet! Today we will move ahead and learn about “fs” module in Nodejs. We will understand this “fs” module, how to use it inside Nodejs with some code samples. This post will be long so please stay tuned and let's code together.

Introduction

If you have some knowledge of working with frontend development or at least you have written some JavaScript code in the browser, you know that the browsers are heavily sandboxed. When you visit a website, you are actually running untrusted code written by strangers and so to prevent your computer from any unwanted peril, browsers are designed to run JavaScript code inside a strict sandbox. Due to this, you can’t simply open a user’s Desktop / Documents folder and start reading their documents.

But Node.js runs on the same Google Chrome’s V8 engine which is responsible for parsing the same JavaScript code. So, using Node.js can you read or write in a document? You might think “No”, but actually this is possible. And in this regard, the “file system” module or “fs” module comes to our rescue. This core module of Node.js gives it the superpower to read, write, update or delete files and folders which exists in our local system or server.

Are you interested to learn how the magic happens? Let’s install Node.js if not done already and learn it together with some real-world examples. As for this example, I am using Node.js v24.19.0.

Reading a file using filesystem module

 Reading a document is a very important feature when it comes to backend development or server-side development. By reading a document, you can fetch the content of the document which can be processed later to produce some desired output.

While working with “fs” module you will come across two different variations of the implementation. The difference comes down to the style of asynchronous control flow the variations provide. In the “node:fs” variant of the “fs” module, you get synchronous and callback-based methods whereas in the “node:fs/promises”, you use asynchronous methods that return promises.

In the Node.js documentation, using the “node:fs/promises” is recommended for modern application development because it seamlessly integrates with async/await and eliminates the overuse of nested callbacks also known as “callback hell.”

Only for this example, we will see how to read a document using both methods but from the next example, we will be only using what the documentation recommends, the “promise” variant.

Example 1: The "node.fs" variant



Exampe 2: The "node:fs/promises" variant



In the first example, first we import the required module “node:fs”. Then we use its “readFile” method to read the document “book.txt”. In the method, we also specify the character encoding “utf-8”. Then we assign a callback to the method. The callback method takes 2 arguments, “err” which is the error object and “data” which is the decoded data object which contains the contents of “book.txt” in simple plain English. If there is any error, we log the error on the console and return. In case, there is not error and data is found, we log it on the console.

As for the second example, we use the “promise” version of the “fs” module. Here, we first import “node:fs/promises”. Then we declare an asynchronous method “readFile” to read the text file and return data. Rest of the code is pretty same as that of the first example. One thing to note here is, always wrap the file operations in a “try-catch” block. In case an error is thrown, the “catch” block can get it and handle it gracefully.

Output (same for both):




As mentioned already, the output for both the code is same. But it is preferrable to go with the "promises" version of the filesystem module.


There are many such functions which the filesystem module can do. Some of the most popular functions along with their brief explanations are mentioned below.

Writing a file using filesystem module




In this example, we write the text "Hello, World!" to a filename "greeting.txt". Here the "writeFile" functions accepts 3 arguments, the filename, the text to write within the file and the character encoding. Here, you need not to manually create the file before writing the content to it. This function will automatically do that for you.

Appending data in a file using filesystem module




In the above example, we append the text "New log entry" along with a new line character in the file "log.txt". This "appendFile" is very same like that of the previously mentioned function "writeFile". The primary difference between the two functions are basically, "appendFile", write content to a file, where some previous content might already exists. But in "writeFile" the previous content is completely replaced.

Checking if a file exists using filesystem module




The "access" is an asynchronous Node.js method used to test a user's permissions for a specific file or directory. It checks file visibility, readability, or writability by testing accessibility constants like F_OK, R_OK, or W_OK. This function, basically checks if the file "book.txt" exists. If it exists, it prints "File exists" on the terminal else it prints "File does not exist:" with the error it ran into.

Renaming a file using filesystem module




fs.rename() is an asynchronous Node.js method used to move or rename a file or directory from an old path to a new path. It updates the filesystem metadata directly, making it a highly efficient and atomic operation on the same partition. In the above example, we are trying to rename the file "book.txt" to "novel.txt". For this we use the "rename" function of the "fs" module.

Delete a file using filesystem module




In the above example, we are trying to delete the file "book.txt" from our current active folder. For this we use the "unlink" function of the "fs" module.

Create a folder using filesystem module




In the above example, we are trying to create a new folder name "myFolder" in the current active folder the code is in. For this we use the "mkdir" function which stands for "make directory".

Read contents a folder using filesystem module




In the above example, we are trying to read the contents of the directory/folder that we just created.

Deleting a folder using filesystem module





In the above example, we are trying to delete the folder "myFolder" that we created few examples back. In the the "rm" or "remove" directory command, we pass "recursive" and "force" as true. This is so that  Node.js delete folders that contain other files and safely ignore errors if the target path does not exist.


This has been a really long blog. In the next post, we will discuss about OS Module, URL Module and many more.

If you are liking my posts please do share with your friends.
And I request everyone to provide your valuable feedback in the comment section as it lets me to improve.



Comments

Popular Posts

Introduction to Node.js

Introduction to Node.js Hello Folks! This blog is for the new Node.js enthusiasts who wants to learn node.js . Here you will learn node.js online from me and you will learn node.js for free . I will guide on how to learn node.js and will help you to learn node.js from scratch. Prerequisites:  Welcome to the world of Back-end web development. Throughout this blog posts, I will guide you to become a backend developer . Before we dive deep into the topic, let us brush up the prerequisites. A website has 2 parts, the "Frontend" and the "Backend" . The Front-end of a website generally refers to the side of the website with which the user interacts. It's the User Interface(U.I.)  of the website. In simple terms, it consists of all those elements which we see and interact with after the web page loads in our computer. It is sometimes also known as "Client-side" of the web page. The Backend web development refers to the server-...

More about Node.js

More about Node.js Hello Folks! Welcome to the part 2 of the Introduction to Node.js blog. Before you read this blog further, it is must to read the previous blogs for better understanding. Here is the  Introduction to Node.js  link. So let's proceed to learn node.js . In this post we will mainly discuss on node.js architecture, the event loop and the thread pool.  Node.js Architecture: As said before, Node.js is  majorly dependent upon the Chrome's V8 engine and LIBUV library for its working. Now I guess you know what is V8 Engine and LIBUV library from the Part 1 of this blog. It is to be mentioned that LIBUV is a library in Node.js which is written in C++ and V8 Engine also uses C++ besides using JavaScript. Therefore, Node.js is not just JavaScript as you might have thought. Now, its time for us to discuss in detail the "Event Loop" and the "Thread Pool" in Node.js. The Event Loop enables Node.js to perform non-blocking I/O operat...

Node.js Modules

Hello Folks! Today we will will move ahead and learn node.js more. We are going to write our first code in node.js today. Then we will discuss about modules in node.js. This post will be long so please stay tuned and let's code together. Initializing the working directory: Open a suitable text editor of your choice. I will use VS Code for the whole series of Node.js to learn Node.js. From FILE , select OPEN FOLDER and select a working directory for your learning. The alternative to this is, right click on the desired working directory and select OPEN WITH CODE. After the working directory has opened we will have to initialize the directory for our Node.js activities. We do it by : >> npm init After that a series of questions are asked as shown in the following picture : We are asked package name, version, description, entry point, test command, git repository,keywords, author and license of our project. Don't worry. Here I have left it empty for ...