Joel Alvarez Myrrie
Joel Alvarez Myrrie

Reputation: 416

Delay using readline in nodejs

function  readFile(){  
  var lineReader = require('readline').createInterface({
    input: require('fs').createReadStream(FILE_PATH)
  });  
  lineReader.on('line', function (line) {
    setTimeout(() => {
      console.log("HEYYYYY");     
    }, 10000);    
  });
}

Why does this only waits 10 seconds once , and the prints 'hey' ? I want to print hey each 10 seconds but it's not working. No idea why.

Edit: This is going to be repeated by the amount of lines that there are on a file (look at the listener 'line') I need to delay 10s between each line.

Upvotes: 2

Views: 4743

Answers (3)

David Callanan
David Callanan

Reputation: 5958

It's because setTimeout does not halt execution, so the next line gets processed immediately. It would be easier to iterate the readline interface using a for await ... of expression, and in here you can await a promise-based timeout function.

Upvotes: 0

user3081601
user3081601

Reputation: 41

I had the same problem and I solved it with the "Example: Read File Stream Line-by-Line" found in: https://nodejs.org/api/readline.html

In your case it would be something like this:

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

    async function processLineByLine() {
    const fileStream = fs.createReadStream(FILE_PATH);

    const rl = readline.createInterface({
      input: fileStream,
      crlfDelay: Infinity
    });
    // Note: we use the crlfDelay option to recognize all instances of CR LF
    // ('\r\n') in input.txt as a single line break.

    for await (const line of rl) {
      // Each line in input.txt will be successively available here as `line`.
      console.log(`Line from file: ${line}`);
      await sleep(10000)
    }
  }

  function sleep(ms){
        return new Promise(resolve=>{
            setTimeout(resolve,ms)
        })
    }

This example would print you a line every 10 seconds.

Upvotes: 4

SunriseM
SunriseM

Reputation: 995

It's not waiting 10 seconds once. its just that each line is read so fast, there's almost not difference in the start time. you can add a variable that increase the delay by 10 seconds in each callback so you each line is print each 10 seconds.

function  readFile(){  

  var delay = 0;  

  var lineReader = require('readline').createInterface({
    input: require('fs').createReadStream(FILE_PATH)
  });  
  lineReader.on('line', function (line) {

    delay += 10000;    

    setTimeout(() => {
      console.log("HEYYYYY");     
    }, 10000+delay);    
  });
}

Upvotes: -1

Related Questions