Skip to content
Related Articles

Related Articles

Improve Article

How to return an array of lines from a file in node.js ?

  • Last Updated : 01 Apr, 2021
Geek Week

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:

  • Read the data of the file using the fs.readFileSync method, you will get a Buffer
  • Convert the Buffer into string Using the toString( ) method
  • Now use the String.split() method to break the data and the delimiter should be “\n”

Below is the Example in which we are implementing the above steps:

index.js




// Requiring the fs module
let 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

Run the code using the command:

node index.js

Output:

[
  'Geeksforgeeks',
  'A computer Science Portal for Geeks'
]
My Personal Notes arrow_drop_up
Recommended Articles
Page :