How to Read a Text File into an Array in Node.js?
Hi friends,
This tutorial will provide an example of how to read a text file into an array in node.js. you'll learn to read a text file into an array in node js. I would like to share with you read a text file into an array in nodejs. This article goes in detailed on read a text file into an array in nodejs. Let's see bellow example nodejs read a text file into an array.
We can read a text file and return its content as an Array using node js. We can use the 'fs' module to deal with the reading of files. The fs.readFile() and 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")
// Intitializing the readFileLines with filename
fs.readFile('readme.txt', function(err, data) {
if(err) throw err;
var array = data.toString().split("\n");
for(i in array) {
// Printing the response array
console.log(array[i]);
}
});
Output:
It will create readme.txt file with following text.
Hello welcome to Nicesnippets.com
- How to Install Node Js and NPM Ubuntu?
- How to used Google ReCaptcha V3 in Node Js Express?
- How to Send Email with Attachment in Node js?
- How to Insert Data from Form into MySQL Database using Node js Express?
- Install Node Js and NPM Ubuntu 18.04/20.04/22.04 Tutorial
- How to Delete Data by id into MongoDB in Node JS?
- Install Node.js 16/17/18 on CentOS 8 Tutorial
- How to Upload File in MongoDB using Node js Express?