简体   繁体   English

延迟在nodejs中使用readline

[英]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' ? 为什么这只等待10秒一次,并且打印“嘿”? I want to print hey each 10 seconds but it's not working. 我想每10秒打印一次嘿,但它不起作用。 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. 编辑:这将通过文件上的行数来重复(查看侦听器“行”),我需要在每行之间延迟10秒。

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 我遇到了同样的问题,并使用以下示例中的“示例:逐行读取文件流”解决了该问题: 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. 本示例将每10秒为您打印一行。

It's not waiting 10 seconds once. 它不会等待10秒一次。 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. 您可以添加一个变量,以在每个回调中将延迟增加10秒,以便每10秒打印一次每一行。

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);    
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM