T
T
Timokins2019-12-12 20:29:13
Algorithms
Timokins, 2019-12-12 20:29:13

What is the best way to mark the last iteration of the loop?

There is a function that takes the path to the file and callback as input,
the function itself asynchronously reads the file line by line and calls the callback with the current line and the value of the end of reading.
How can we improve the transmission of information about the last line without calling callback with an empty string?
a simple example to illustrate:

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

async function read(filepath, callback) {
  const fileStream = fs.createReadStream(filepath);

  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity
  });

  for await (const line of rl) {
    await callback(line, false);
  }

  // ?????????????????
  await callback(null, true);
}

read('./hello.json', (line, done) => {
  console.log(line, done);
});

while it comes to mind to create a queue of lines and, when reading, give not the current line, but the previous one, and then already on the last line I will know that it is the last one, but an additional callback call after the loop will remain
whether there are more suitable solutions to understand that the last line is the last one?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question