const fs = require('fs');
const path = require('path');
// Create a sample file
const readableFile = path.join(__dirname, 'readable-example.txt');
fs.writeFileSync(readableFile, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.repeat(100));
// Create a ReadStream without auto-flowing
const readStream = fs.createReadStream(readableFile, {
highWaterMark: 32 // Small buffer to demonstrate multiple reads
});
console.log('Using the readable event and read() method:');
// Using the 'readable' event for manual reading
readStream.on('readable', () => {
let chunk;
// read() returns null when there is no more data to read
while (null !== (chunk = readStream.read(16))) {
console.log(`Read ${chunk.length} bytes: ${chunk.toString('utf8').substring(0, 10)}...`);
}
});
readStream.on('end', () => {
console.log('End of stream reached');
// Clean up the sample file
fs.unlinkSync(readableFile);
console.log('Sample file removed');
});
readStream.on('error', (err) => {
console.error(`Error: ${err.message}`);
});