2

I have my following code:

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

What this does is wait 2 seconds in the beginning and then outputs all the chunks together. What I want to do is everytime a chunk is read and output I want it to wait to 2 seconds before next read and output. How do I modify my code?

1 Answers1

3

To control the flow of a stream, you can use .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()
})

You can also use readable event instead, and call read when you're ready to get the next chunk:

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

The while loop is necessary when processing data with readable.read(). Only after readable.read() returns null, 'readable' will be emitted.

Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98