Skip to content

Instantly share code, notes, and snippets.

@Lazhari
Created September 9, 2018 00:47
Show Gist options
  • Save Lazhari/b8e38b3b15b4dedf3616163ca4c84a51 to your computer and use it in GitHub Desktop.
Save Lazhari/b8e38b3b15b4dedf3616163ca4c84a51 to your computer and use it in GitHub Desktop.
Duplex Stream with Node.js
const { PassThrough, Duplex } = require("stream");
const { createReadStream, createWriteStream } = require("fs");
const readStream = createReadStream("../../powder-day.mp4");
const writeStream = createWriteStream("./copy.mp4");
class Throttle extends Duplex {
constructor(ms) {
super();
this.delay = ms;
}
_write(chunk, encoding, callback) {
this.push(chunk);
setTimeout(callback, this.delay);
}
_read() {}
_final() {
this.push(null);
}
}
const report = new PassThrough();
const throttle = new Throttle(10);
let total = 0;
report.on("data", chunk => {
total += chunk.length;
console.log("bytes: ", total);
});
readStream
.pipe(throttle)
.pipe(report)
.pipe(writeStream);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment