9

I want to read a text file (.txt) using Node.js. I need to push each of text's lines into array, like this:

a
b
c

to

var array = ['a', 'b', 'c'];

How can I do this?

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
JustLogin
  • 1,822
  • 5
  • 28
  • 50

1 Answers1

28

You can do this :

var fs  = require("fs");
var array = fs.readFileSync(path).toString().split('\n');

Or the asynchronous variant :

var fs  = require("fs");
fs.readFile(path, function(err, f){
    var array = f.toString().split('\n');
    // use the array
});
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758