Reading local text file into a JavaScript array

JavascriptText

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWilliam RossView Question on Stackoverflow
Solution 1 - JavascriptsiavoltView Answer on Stackoverflow