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
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):
Writing a file using filesystem module
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
Renaming a file using filesystem module
Delete a file using filesystem module
Create a folder using filesystem module
Read contents a folder using filesystem module
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.












Comments
Post a Comment