我有以下代码:

var fs = require('fs');
var myReadStream = fs.createReadStream('readMe.txt')
myReadStream.on('data', function(data_chunk){
   setTimeout(function(){
   console.log('chunk read:')
   console.log(data_chunk)
   },2000)
})


这样做是在开始时等待2秒钟,然后将所有块一起输出。我想做的是每次读取和输出一个块时,我都希望它等待2秒钟才能下次读取和输出。如何修改我的代码?

最佳答案

要控制流的流,可以使用.pause().resume()

myReadStream.on('data', async function(data_chunk){
   myReadStream.pause();

   console.log('chunk read:')
   console.log(data_chunk)
   await new Promise(resolve => setTimeout(resolve, 2000));

   myReadStream.resume()
})


您还可以改用readable事件,并在准备获取下一个块时调用read

myReadStream.on('readable', async function(){
   await new Promise(resolve => setTimeout(resolve, 2000));

   while (null !== (chunk = myReadStream.read())) {
      console.log('chunk read:')
      console.log(chunk)
      await new Promise(resolve => setTimeout(resolve, 2000));
   }
})



  使用read.read()处理数据时,需要while循环。
  只有在read.read()返回null之后,才会发出“可读”。

09-25 18:01