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?
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.
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.
The string in JavaScript can be converted into a character array by using the split() and Array. from() functions.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With