JavaScript

How to Read File Content as a String in Node.js?

Read and write files are the common operations of the Node.js built-in File System(fs) module. The “fs” module performs these tasks with the help of its built-in synchronous and asynchronous methods. All these methods first store the content of the file into a buffer and then return it as an output. The buffer is the particular memory location that stores the data in binary digits. This data is not in the human-readable format. So, the user needs to convert the entire file data into a string to make it readable.

This post will explain how to read file content as a string in Node.js with the following list of contents:

Sample File

Before moving on to the practical implementation, look at the given sample file whose entire content will be read as a string:

Press “Ctrl+S” to save and “Ctrl+X” to close the file.

Now, read the above file content into a string format using the “fs.readFile()” method.

Method 1: Read File Content as a String Using “fs.readFile()”

The “fs.readFile()” is the simplest pre-defined method that reads file in Node.js. It performs this task by utilizing its basic syntax that is written here:

fs.readFile( filename, encoding-type, callback_function )

 

The above syntax shows that the “fs.readFile()” method works on the following three parameters:

  • filename: It specifies the name of the file or its absolute path where it is placed.
  • encoding-type: It denotes the encoding type that is “utf8” by default. If it is not mentioned then the “fs.readFile()” method returns the entire data as a buffer(binary/hex/ascii or many other formats )
  • callback_function: It defines a call-back function that executes after reading the specified file. It supports two parameters “err(If an error occurs)” and “data(the content of the sample file)”.

Now, implement the above-defined method practically.

Example 1: Apply “fs.readFile()” Method With “encoding(utf8)” Parameter to Read File Content as a String

This example applies the “fs.readFile()” method with the “utf8” encoding parameter to read a file as a string:

const fs = require("fs");
fs.readFile("file.txt", "utf8" ,(err, data) => {
if (err) {
 console.error(err);
 return;
}
console.log(data);
});

 

In the above code snippet:

  • Firstly, the “fs” variable imports the File System module(fs) via the “require()” method.
  • Next, the “readFile()” method specifies the given text file as its first argument, the encoding type “utf8” as the second argument, and the “call-back” function as the third argument.
  • The call-back function also specifies two default parameters “err” and “data”.
  • In this function definition, an “if” statement is specified that displays the error message(if occurs) by using the “console.error()” method. If an error does not occur then the “console.log()” method is utilized that show the data of the specified file:

Output(Without “utf8” String Format)

Execute the below-stated command to initiate the “.js” file:

node app.js

 

It can be seen that without specifying the “utf8” string format in the “readFile()” method, the content of the specified file shows like a buffer:

Output(With “utf8” String Format)

Now, run the following command to execute the “app.js” file. This time “readFile() method will use the “utf8” format to display the file content as a string as shown in the above code:

node app.js

 

It can be observed that the file content has been shown as a string:

Example 2: Apply “fs.readFile()” Along With “toString()” Method to Read File Content as a String

This example utilizes the “toString()” method along with the “fs.readFile()” to show the sample file content as a string:

const fs = require("fs");
fs.readFile("file.txt", (err, data) => {
if (err) {
 console.error(err);
 return;
}
console.log(data.toString());
});

 

In the above code lines:

  • The “toString()” method is applied as an argument of the “console.log()” method to display the specified file “data” as a string.
  • For instance, the “utf8” parameter is not specified because of the “toString()” method:

Save the above file.

Output

Execute the given command to run the “.js” file:

node app.js

 

The output is identical to example 1(utf8 format) i.e. reading the file content as a string:

Method 2: Read File Content as a String Using “fs.readFileSync()”

Another way to read a file in Node.js is the “fs.readFileSync()” method. It is an alternative to the “fs.readFile()” method with only one difference it reads the file in a synchronous way by blocking all other parallel processes.

Moreover, It follows the same parameter as the “fs.readFile()” method. Therefore the user can use both the “utf8” and the “toString()” method along with the “fs.readFileSync()” in the same way as performed in the “fs.readFile()” method.

Note: To utilize this method, follow the “Read a File Synchronously with fs.readFileSync()” detailed guide.

That’s all about reading a file content as a string in Node.js.

Conclusion

To read file content as a string use the “utf8(encoding)” parameter or the “toString()” along with the Node.js “fs.readFile()” method. These approaches can also be used with the “fs.readFileSync()” method. If the user does not use the defined ways then the “fs.readFile()”, and the “fs.readFileSync()” method returns the file content as a buffer. This post has explained all possible methods to read file content into the string format in Node.js.

About the author

Areej Nadeem

I am a technical author holding a Bachelor’s degree in Computer Science. I am passionate about writing and learning new technologies and sharing my knowledge with the rest of the world.