Convert library function to generator

Viewed 41

lets say we have library that reads file line by line like this:

var lines = lib.open('file.txt');
lines.on('line', function(line) {
    console.log(line);
});

Is there any way to wrap the code and create generator that could be used with "for of" loop:

for (let line of lines) {
    console.log(line);
}

lines.on('line', function(line) {
    yield line; // doesnt work inside the function
    console.log(line);
});

If i yield inside the function it doesn't work.

Thanks

1 Answers

You can use for await of loop on stream

async function read(lines) {

for await (const line of lines) {
    console.log('>>> ',line);
  }

}
var lines = lib.open('file.txt');

read(lines)

From chunks to lines
The following function takes an async iterable over strings and returns an async iterable over lines:

   async function* chunksToLines(chunksAsync) {
      let previous = '';
      for await (const chunk of chunksAsync) {
        previous += chunk;
        let eolIndex;
        while ((eolIndex = previous.indexOf('\n')) >= 0) {
          // line includes the EOL
          const line = previous.slice(0, eolIndex+1);
          yield line;
          previous = previous.slice(eolIndex+1);
        }
      }
      if (previous.length > 0) {
        yield previous;
      }
    }

Read this out for more details:

Related