How to return an array of lines from a file in node.js ?
Last Updated :
23 Jul, 2025
In this article, we will return an array of lines from a specified file using node.js. The fs module is used to deal with the file system in node.js and to read file data we use fs.readFileSync( ) or fs.readFile( ) methods. Here we will use the readFileSync method to read the file, and we use the steps below to return the lines of the file in an array:
Using fs.readFileSync and split method
To return an array of lines from a file in Node.js, we will
- Read the data of the file using the fs.readFileSync method, you will get a Buffer
- Convert the Buffer into a string Using the toString( ) method
- Now use the String.split() method to break the data and the delimiter should be "\n"
Example:
Below is the Example in which we are implementing the above steps:
JavaScript
// Requiring the fs module
const fs = require("fs")
// Creating a function which takes a file as input
const readFileLines = filename =>
fs
.readFileSync(filename)
.toString('UTF8')
.split('\n');
// Driver code
let arr = readFileLines('gfg.txt');
// Print the array
console.log(arr);
Text file: The gfg.txt file.
Geeksforgeeks
A computer Science Portal for Geeks
Steps to Run the Code: use the following the command
node index.js
Output:
[
'Geeksforgeeks',
'A computer Science Portal for Geeks'
]
Using readline for Large Files
This approach uses the readline module to read a file line-by-line, storing each line in an array, which is then returned via a callback function once the file reading is complete.
Example:
Node
// Requiring the fs and readline modules
const fs = require("fs");
const readline = require("readline");
// Creating a function which takes a file as input
const readFileLinesReadline = (filename, callback) => {
const lines = [];
const readInterface = readline.createInterface({
input: fs.createReadStream(filename),
output: process.stdout,
console: false
});
readInterface.on('line', (line) => {
lines.push(line);
});
readInterface.on('close', () => {
callback(null, lines);
});
readInterface.on('error', (err) => {
callback(err);
});
};
// Driver code
readFileLinesReadline('gfg.txt', (err, arrReadline) => {
if (err) {
console.error(err);
return;
}
// Print the array
console.log(arrReadline);
});
Output:
[
'Geeksforgeeks',
'A computer Science Portal for Geeks'
]
Explore
Introduction & Installation
Node.js Modules , Buffer & Streams
Node.js Asynchronous Programming
Node.js NPM
Node.js Deployments & Communication
Resources & Tools