31-Aug-2022
.
Admin
Hi friends,
This article will provide some of the most important examples of how to read a text file in node.js. In this article, we will implement a read a text file in node js. This article goes in detailed on read a text file in nodejs example. step by step explain read a text file in node.js example. Alright, let’s dive into the steps.
We can read a text file and return its content using node js. We can use the 'fs' module to deal with the reading of file. The fs.readFileSync() methods are used for the reading files.
So, let's start follwing example with output:
Step 1: Create Node.js Project
This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:
mkdir my-app
cd my-app
npm init
Step 2: Update index.js File
index.js
// Importing the fs module
fs = require('fs');
try {
// Intitializing the readFileLines with filename
var data = fs.readFileSync('readme.txt', 'utf8');
// Printing the response
console.log(data.toString());
}catch(e) {
// Printing error
console.log('Error:', e.stack);
}
Output:
you can read readme.txt file with following text.
Hello welcome to Nicesnippets.com
I hope it can help you...
#Node JS