I have a text file of a ton of words that are seperated by a newline e.g.
hello
goodbye
Jim ran
what
is
the
name
etc.
I need to put these words into a Javascript array. Is there any easy way to do this? I tried copying and pasting it into a variable in a node prompt and then I was going to split it at the newlines, but that did not work because the prompt couldn't handle such a long string. Any ideas?
Here is one way:
var fs = require('fs');
var txt = fs.readFileSync('file.txt', {encoding: 'utf8'});
var arr = txt.split('\r\n');
console.dir(arr);
I know the op is asking for splitting it into an array, but if the file is large or an incoming stream it might be worthwhile using a stream and byline so you can write something like this:
var fs = require('fs'),
byline = require('byline');
var stream = byline(fs.createReadStream('sample.txt'));
//The data event then emits lines:
stream.on('data', function(line) {
console.log(line);
});