Table of contents
INTRODUCTION
The 'Fs' module is a very versatile module of Javascript. It helps us to perform read, write, and append operations on the file. In this article we will see how to read a file, using the Fs module.
READING FILE
So for this article, we will perform all the operations on the file named 'saksham.txt'. Let me show you the contents of the file.
Now let's see how to perform a read operation on this '.txt' file using the Fs module. Here is the code.
In the first line, I created an instance of the Fs module. Here syntax you can see in the snippet, I will explain the main part. First parameter inside the readFile
should be the name of the file you want to read. In my case file was in the same directory, so only name was required. In case the file is in some other directory, you have to give the full path.
The second parameter is a function, which has two inbuilt parameters, err-->(error), data-->(data), you can name them according to your wish, but they should be in the same order. While logging the data, you must apply toString()
, to convert data into readable format. The read operation, which we performed above was the asynchronous read operation. If you want to read about Asynchronous and Synchronous operations, then refer to my Article:- Asynchronous and Synchronous operations. If we want to perform the same task in a Synchronous manner, we need to do a slight change,
Here, we have to use readFileSync
rather than readFile
. In readFile
, we get data from a callback, but readFileSync
returns the data. All the other things are the same.