Created
August 19, 2019 06:20
-
-
Save MelodicCrypter/ad949bc0158689270b5f28e99b9ddcbd to your computer and use it in GitHub Desktop.
NodeJS sample for copying files using streams with backpressure.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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