Get your own Node server
const fs = require('fs');
const path = require('path');

// Create a large sample file for the flow control example
const flowFile = path.join(__dirname, 'flow-control-example.txt');
let sampleContent = '';
for (let i = 1; i <= 1000; i++) {
  sampleContent += `This is line ${i} of the test file.\n`;
}
fs.writeFileSync(flowFile, sampleContent);

// Create a ReadStream
const readStream = fs.createReadStream(flowFile, {
  encoding: 'utf8',
  highWaterMark: 1024 // 1KB buffer
});

let chunkCount = 0;
let totalBytes = 0;
let isPaused = false;

// Handle data chunks with flow control
readStream.on('data', (chunk) => {
  chunkCount++;
  totalBytes += chunk.length;
  
  console.log(`Chunk #${chunkCount} received, size: ${chunk.length} bytes`);
  
  // Pause the stream every 5 chunks to demonstrate flow control
  if (chunkCount % 5 === 0 && !isPaused) {
    console.log('\nPausing the stream for 1 second...');
    isPaused = true;
    
    // Pause the stream
    readStream.pause();
    
    // Resume after 1 second
    setTimeout(() => {
      console.log('Resuming the stream...\n');
      isPaused = false;
      readStream.resume();
    }, 1000);
  }
});

readStream.on('end', () => {
  console.log(`\nFinished reading file. Received ${chunkCount} chunks, ${totalBytes} bytes total.`);
  
  // Clean up the sample file
  fs.unlinkSync(flowFile);
  console.log('Sample file removed');
});

readStream.on('error', (err) => {
  console.error(`Error: ${err.message}`);
});

              
Chunk #1 received, size: 1024 bytes
Chunk #2 received, size: 1024 bytes
Chunk #3 received, size: 1024 bytes
Chunk #4 received, size: 1024 bytes
Chunk #5 received, size: 1024 bytes

Pausing the stream for 1 second...
Resuming the stream...

Chunk #6 received, size: 1024 bytes
Chunk #7 received, size: 1024 bytes
Chunk #8 received, size: 1024 bytes
Chunk #9 received, size: 1024 bytes
Chunk #10 received, size: 1024 bytes

Pausing the stream for 1 second...
Resuming the stream...

[... more chunks ...]

Finished reading file. Received 24 chunks, 24576 bytes total.
Sample file removed