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

為什么這只等待10秒一次,並且打印“嘿”? 我想每10秒打印一次嘿,但它不起作用。 不知道為什么。

編輯:這將通過文件上的行數來重復(查看偵聽器“行”),我需要在每行之間延遲10秒。

我遇到了同樣的問題,並使用以下示例中的“示例:逐行讀取文件流”解決了該問題: https : //nodejs.org/api/readline.html

在您的情況下,將是這樣的:

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

本示例將每10秒為您打印一行。

它不會等待10秒一次。 只是每行的讀取速度如此之快,開始時間幾乎沒有差別。 您可以添加一個變量,以在每個回調中將延遲增加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