Skip to content

Instantly share code, notes, and snippets.

@PaulMougel
Created December 14, 2013 16:34
Show Gist options
  • Save PaulMougel/7961469 to your computer and use it in GitHub Desktop.
Save PaulMougel/7961469 to your computer and use it in GitHub Desktop.
Buffered Transform stream — simple PassThrough stream that also keeps an internal buffer. When a stream is piped into the BufferStream, the internal buffer is written to the new piped stream; after that the BufferStream behaves like a PassThrough.
dd if=/dev/zero of=input.txt bs=512k count=50
var fs = require('fs')
var util = require('util')
var stream = require('stream')
var BufferStream = function (streamOptions) {
stream.Transform.call(this, streamOptions)
}
util.inherits(BufferStream, stream.Transform)
BufferStream.prototype.pipe = function (destination, options) {
var res = BufferStream.super_.prototype.pipe.call(this, destination, options)
if (this.buffer)
res.write(this.buffer)
return res
}
BufferStream.prototype._transform = function (chunk, encoding, done) {
this.buffer = new Buffer(chunk)
this.push(chunk)
done()
}
var input = fs.createReadStream('input.txt')
var buffer = new BufferStream()
input.pipe(buffer)
setTimeout(function () {
buffer.pipe(fs.createWriteStream('output1.txt'))
}, 1)
setTimeout(function () {
buffer.pipe(fs.createWriteStream('output2.txt'))
}, 50)
@ORESoftware
Copy link

nice work

@ORESoftware
Copy link

I implement the following based off your code https://gist.github.com/ORESoftware/e733e03334d885c9249b81866ed5b9b9, do you see anything wrong with it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment