Home > other >  Node.js: Any way to stop reading the file and the whole process in line-reader's eachLine funct
Node.js: Any way to stop reading the file and the whole process in line-reader's eachLine funct

Time:11-05

I have this code:

const lineReader = require('line-reader');

var truevar = false;

async function readLines(filename, processLine) {
    return new Promise((resolve, reject) => {
        lineReader.eachLine(filename, (line, last, callback) => { 
           if (!callback) throw new Error('panic');
               if (truevar) {
                   // I wanna stop/finish the function here
               } else {
                   processLine(line)
                   .then(() => last ? resolve() : callback())
                   .catch(reject);
               };
           });
       })
   };

And here's how I call the readLines function:

await readLines('somefile.txt', async (line) => {
    await delay(1000) // 1 second
    other_function(line);
});

I need to stop reading the file & finish the entire process once it gets to a certain point. I've read the line-reader docs, but found nothing. I also tried to do it the dirty way with "break;" etc but it's obviously just not gonna finish the job and be stuck (can't call it again unless I reload the program) so that's useless.

EDIT: Fixed the problem. I forgot to set the truevar back to false, in order to be able to call the function again.

CodePudding user response:

Try this:

lineReader.eachLine(filename, (line, last, callback) => { 
  if (!callback) throw new Error('panic');
  if (truevar) {

    // Add to stop reading
    cb(false);        

  } else {
    processLine(line)
      .then(() => last ? resolve() : callback())
      .catch(reject);
  };
});

Source: https://www.npmjs.com/package/line-reader

CodePudding user response:

Found out why I wasn't able to call the function again. It wasn't the issue with async function not being stopped properly, I just didn't set the truevar back to false, in order to be able to call the function again.

  • Related