Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 915
William Ross Avatar asked Jan 18 '16 14:01

William Ross


People also ask

How do you duplicate an array in JavaScript?

To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.

How do you read a file in JavaScript?

To read a file, use FileReader , which enables you to read the content of a File object into memory. You can instruct FileReader to read a file as an array buffer, a data URL, or text. // Check if the file is an image.

How do you turn a string into an array in JavaScript?

The string in JavaScript can be converted into a character array by using the split() and Array. from() functions.


1 Answers

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"); 
like image 163
siavolt Avatar answered Sep 20 '22 01:09

siavolt