66

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?

William Ross
  • 3,568
  • 7
  • 42
  • 73
  • 8
    This "Javascript - read local text file" question/answer looks like a good place to start: http://stackoverflow.com/questions/14446447/javascript-read-local-text-file – Marc Jan 18 '16 at 14:48
  • 2
    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? – Quentin Jan 18 '16 at 14:50
  • Is it for server side(Node) or client side(web-browser)? You can't do it for client side coding. – Lutfar Rahman Milu Jan 18 '16 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? – William Ross Jan 18 '16 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. – William Ross Jan 18 '16 at 15:00

1 Answers1

114

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");
gmelodie
  • 411
  • 4
  • 18
siavolt
  • 6,869
  • 5
  • 24
  • 27