70

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?

5
  • 8
    This "Javascript - read local text file" question/answer looks like a good place to start: stackoverflow.com/questions/14446447/… Commented Jan 18, 2016 at 14:48
  • 3
    What is your JavaScript running? Is it embedded in a webpage? Does "local" mean "on the same HTTP host"? Or are you running it with Windows Scripting Host? Or Node.js? And wanting to access your file system rather than something over HTTP? Commented Jan 18, 2016 at 14:50
  • Is it for server side(Node) or client side(web-browser)? You can't do it for client side coding. Commented Jan 18, 2016 at 14:53
  • 1
    I just have both the .js file and the .txt file locally. I'm trying to get it working locally first before deploying it on the web... but it sounds like it cannot work that way locally? Commented Jan 18, 2016 at 14:54
  • 3
    @dan-man, i saw the linked solution that Marc posted. Do I need to communicate over http to read the txt file? It seems like that solution is already deployed on the web though. Commented Jan 18, 2016 at 15:00

1 Answer 1

119

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");
Sign up to request clarification or add additional context in comments.

11 Comments

how to put them into an array ?
Split function returns an array, and textByLine is already an array
This doesn't appear to work on Node 6, which returns a Buffer
This gives me an "Uncaught ReferenceError: require is not defined"! What am I missing?
The question clearly does not specify that Node.js is being used. This answer is a Node.js answer.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.