0

I am using readline rd.on('line', function(line) {..... to read in a file line by line. I want to then just consume the file one line at a time starting from the first line and proceeding to the end of the file.

It seems "unshift" on an Array (in order to create a Queue to retain the order) can only take a literal and not a variable.

The main and apparently simplest solution I see for this is to read the file and process int into a string and split(\n) into an array.

Is there a "better" way? This seems to consume a huge amount of memory and has limits as a result.

GreenGiant
  • 4,930
  • 1
  • 46
  • 76
JHS
  • 21
  • 7
  • 1
    Why would you read it in line by line, and then loop through the lines again? Why not just do whatever you want to do the first time through, inside your `function(line) {...}` function? – forgivenson Apr 22 '16 at 17:00
  • you cannot read file in Javascript – CY5 Apr 22 '16 at 17:01
  • @CY5 Yes you can. In addition to what forgivenson said, what do you mean "unshift on an Array [...] can only take a literal?" Anything that's a literal can be a variable. – Mike Cluck Apr 22 '16 at 17:02
  • Also, `unshift` can handle a variable just fine. – forgivenson Apr 22 '16 at 17:02
  • @CY5 readline is a node module, so I'm assuming the OP is using NodeJS. – forgivenson Apr 22 '16 at 17:04
  • The FileReader API is a great way to work with files in JS https://developer.mozilla.org/en-US/docs/Web/API/FileReader – Vitor Rigoni Apr 22 '16 at 17:41
  • @CY5 [Yes you can](http://stackoverflow.com/questions/4950567/reading-client-side-text-file-using-javascript/4950836#4950836) even on the client side – Ruan Mendes Apr 22 '16 at 17:44
  • @JuanMendes and Mike Thanks for that i was aware of only xmlhttprequest to load a file – CY5 Apr 22 '16 at 17:52

1 Answers1

2

There is no reason to push your lines after reading them into an array only to read them again. When handling the line event emitted from the readline module simply process the line then.

Here is the excerpt from the Readline module docs on how to read a file line-by-line:

A common case for readline's input option is to pass a filesystem readable stream to it. This is how one could craft line-by-line parsing of a file:

const readline = require('readline');
const fs = require('fs');

const rl = readline.createInterface({
  input: fs.createReadStream('sample.txt')
});

rl.on('line', (line) => {
  console.log('Line from file:', line);
});
Matt Browne
  • 12,169
  • 4
  • 59
  • 75
peteb
  • 18,552
  • 9
  • 50
  • 62