What is the mechanism of reading the content of a file in Node.js ?
In this article, we will discuss the mechanism of reading a file in NodeJs.
If you want to more about file systems in NodeJs please refer to this article.
Mechanism of reading a file in NodeJS: In Node.js, you can work with files with the help of a built-in “fs” module and it’s very simple. and this module includes all functionality that will help you to work with files, And it can operate with both types of files on a local machine or server. And it gives you two types of facilities, which have the ability to work synchronously and asynchronously, you can use it in any NodeJs file and for this, there is no need for any external package.
Approach: Have to work with the file system, so the ‘fs’ module will be needed first, so require the ‘fs’ module in our codebase. The read method of the ‘fs’ module return buffer data, which will require a variable to hold. The buffer will store the data on a variable. Convert the buffer data to the normal string with the help of the toString() method. Finally log the data using the console.log() method.
Below is the step by step implementation of the above approach:
Step 1: First, let’s require a file system module into our program for reading the data from a file.
const fs = require('fs');
After requiring the ‘fs’ module moves to the second step.
Step 2: In this step create a variable to contain the data of a file.
let dataBufferContainer= '';
Step 3: After making the variable, store the file buffer data to the variable in the use of the readFileSync or readFile Method.
dataBufferContainer = fs.readFileSync('file.js');
Step 4: Convert buffer value to the normal string value with the use of the toString() method.
let data = dataBufferContainer.toString();
Step 5: Log the data using the console.log() method.
Finally, you have read the data from the file.
Below is the implementation of the above approach:
Step to run the application: