1

i´m writting a little parser in nodejs which translates a given assembly language into binary code. Ironically I struggle with the line reading. What I want is the possibility to read a file line by line (like the readline.createInterface) Module BUT it should only advance in lines when I invoke a function.

I.E

1.) While LastChunkNotReached
 1.1) Read chunk
 1.2) Split chunk into lines and save into buffer
    2.) While last line in buffer not reached
     2.1) return actual line somehow and wait for the user to invoke a function to 
          advance to the next line. 
    2.) End
1.) End

In case of the readable event (which may be the only valid starting point for me) you can gather the chunks while invoking the stream.read() function.

stream.on("readable", () => {
    console.log("Data available");
    const data = stream.read();
    console.log("Data read: " + data)
})

But the problem with this approach is the following (as far as I observed it): When I use the read function, it returns a chunk from the internal buffer, but now the readable event gets fired everytime the internal buffer has new fresh data (which in turn calls the .read() function)

Is there a clean way to intercept this behaviour to get to the point which I described above? Would be nice if you can give me some thoughts or tips about this problem!

Byte
  • 71
  • 3
  • Searching for "nodejs read file line by line" would have been more than sufficient to answer this. – Dave Newton Oct 13 '18 at 14:09
  • They all answer the question how to read line by line(fs.createInterface as i mentiond in my post) but not how to read a line and stop execution until someone wants the next line – Byte Oct 13 '18 at 14:34
  • Not relevant-you're processing each line as it comes in. Why would you ever need to stop and wait? – Dave Newton Oct 13 '18 at 14:44
  • @Byte I found a prominent answer in an another question here: https://stackoverflow.com/a/42867871/1330083 You might wanna give it a try. – maksbd19 Oct 14 '18 at 04:25
  • I think i cant explain my problem very well because of my bad english. But I will look into the answer from @maksbd19. Sorry for the trouble – Byte Oct 17 '18 at 11:43

1 Answers1

1
  var readline = require('readline');
  var fs = require('fs');

  var myInterface = readline.createInterface({
      input: fs.createReadStream('demo.txt')
  });

  var lineno = 0;
  myInterface.on('line', function (line) {
     lineno++;
     console.log('Line number ' + lineno +" > "+ line);
  });
cegenedici
  • 11
  • 2
  • 1
    And how do you pause/resume the execution after each line? – Byte Oct 13 '18 at 14:32
  • @Byte ... Why would you want to? You process each line as it's available, it's no different than reading a line, processing it, and reading another line, etc. You're either not describing the issue well, or you're not comfortable with async programming. – Dave Newton Oct 13 '18 at 15:01