Skip to content

Instantly share code, notes, and snippets.

@piscisaureus
Created July 19, 2013 21:04
Show Gist options
  • Save piscisaureus/6042325 to your computer and use it in GitHub Desktop.
Save piscisaureus/6042325 to your computer and use it in GitHub Desktop.
fast.js
var WriteStream = require('fs').WriteStream;
var BUF_SIZE = 1 * 1024 * 1024;
var CHUNK_MAX = 100 * 1024;
WriteStream.prototype.__write = WriteStream.prototype.write;
WriteStream.prototype.__end = WriteStream.prototype.end;
WriteStream.prototype.__flush = function() {
if (this.__writeBehindBuffer &&
this.__writeBehindUsed) {
this.__write(this.__writeBehindBuffer.slice(0, this.__writeBehindUsed));
this.__writeBehindBuffer = null;
this.__writeBehindUsed = 0;
}
}
WriteStream.prototype.write = function(chunk, encoding, cb) {
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
// No string support for now
// Also if the chunk is very big, don't buffer
if (!Buffer.isBuffer(chunk) ||
chunk.length > CHUNK_MAX) {
this.__flush();
return this.__write(chunk, encoding, cb);
}
var left = this.__writeBehindBuffer ?
this.__writeBehindBuffer.length - this.__writeBehindUsed : 0
if (left < chunk.length) {
this.__flush();
this.__writeBehindBuffer = new Buffer(BUF_SIZE);
this.__writeBehindUsed = 0;
}
chunk.copy(this.__writeBehindBuffer, this.__writeBehindUsed);
this.__writeBehindUsed += chunk.length;
}
WriteStream.prototype.end = function(chunk, encoding, cb) {
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (chunk)
this.write(chunk, encoding);
this.__flush();
this.__end(cb);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment