Reading local text file into a JavaScript array [duplicate]
I have a text file in the same folder as my JavaScript file. Both files are stored on my local machine. The .txt file is one word on each line like:
red
green
blue
black
I want to read in each line and store them in a JavaScript array as efficiently as possible. How do you do this?
Using Node.js
sync mode:
var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")
async mode:
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
UPDATE
As of at least Node 6, readFileSync
returns a Buffer
, so it must first be converted to a string in order for split
to work:
var text = fs.readFileSync("./mytext.txt").toString('utf-8');
Or
var text = fs.readFileSync("./mytext.txt", "utf-8");