Skip to content

Instantly share code, notes, and snippets.

@MelodicCrypter
Created August 19, 2019 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MelodicCrypter/ad949bc0158689270b5f28e99b9ddcbd to your computer and use it in GitHub Desktop.
Save MelodicCrypter/ad949bc0158689270b5f28e99b9ddcbd to your computer and use it in GitHub Desktop.
NodeJS sample for copying files using streams with backpressure.
const { createReadStream, createWriteStream} = require('fs');
// You should include a real file live video, image, etc
const readStream = createReadStream(__dirname+'/powder-day.mp4');
const writeStream = createWriteStream(__dirname+'/copy.mp4', { highWaterMark: 1628920 });
// => flowing stream
readStream.on('data', (chunk) => {
// if this will be false, meaning the stream is full
const result = writeStream.write(chunk);
// pause the flow temporarily
if (!result) {
console.log('backpressure');
readStream.pause();
}
});
readStream.on('end', () => {
writeStream.end();
});
readStream.on('error', (err) => {
console.log(`====> ${err}`);
});
// if the stream is ready or empty, pour some stream again
// note this is on writeStream, not on readStream
writeStream.on('drain', () => {
console.log('drained');
readStream.resume();
});
writeStream.on('close', () => {
process.stdout.write('file copied');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment