Home > Blockchain >  Get first element of an async iterable
Get first element of an async iterable

Time:06-05

On nodejs, I’m trying to get the first line of a file. For that, I’m using the readline package as mentioned in this answer.

But since I’m only trying to get the first line, I’d need to get the readline object to output its first element. I found how to do that in this answer, but it looks like it only works for synchronous iterators.

How do you get the first element of an async iterator?

CodePudding user response:

Just return in the first iteration of the loop? Copying some code from that answer, and making sure to destroy the stream after you're done with getting only the first line:

async function processLineByLine() {
  const fileStream = fs.createReadStream('input.txt');
  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity
  });
  for await (const line of rl) {
    fileStream.destroy();
    return line;
  }
}

and then processLineByLine will return a Promise that resolves to the content in the first line.

  • Related