UNPKG

fsk-imgoptimize

Version:
90 lines (86 loc) 2.39 kB
var Writable = require('stream').Writable; var Readable = require('stream').Readable; var util = require('util'); util.inherits(ImgOptimize, Readable); var _keys = Object.keys(Writable.prototype); for(var v = 0, len = _keys.length; v < len; v++) { var method = _keys[v]; if (!ImgOptimize.prototype[method]) { ImgOptimize.prototype[method] = Writable.prototype[method]; } } function ImgOptimize(options) { if (!(this instanceof ImgOptimize)) { return new ImgOptimize(options); } Writable.call(this, options); Readable.call(this, options); this.writable = true; this.readable = true; options = options || {}; if (options.writable === false) { this.writable = false; } if (options.readable === false) { this.readable = false; } this._encoding = options.encoding; this._buffers = []; this._constants = null; this._size = 0; this._queue = []; this.handleSignature(); } ImgOptimize.prototype._read = function(length) { }; ImgOptimize.prototype.write = function(data, encoding) { if (!this.writable) { throw new Error('cannot write'); } if (!util.isBuffer(data)) { data = new Buffer(data, encoding || this._encoding); } this._buffers.push(data); this._size += data.length; this._process(); }; ImgOptimize.prototype._process = function() { while(this._queue.length && this._buffers.length && this._size > 0) { var chunk = this._queue[0]; var len = chunk.length; if (chunk && len <= this._size) { this._queue.shift(); var pos = 0; var index = 0; var buffer = new Buffer(len); while (pos < chunk.length) { var current = this._buffers[index++]; var minLen = Math.min(len - pos, current.length); current.copy(buffer, pos, 0, minLen); pos += minLen; if (minLen !== current.length) { this._buffers[--index] = current.slice(minLen); } } if (index) { this._buffers.splice(0, index); } this._size -= len; chunk.callback.call(this, buffer); } else { break; } } }; ImgOptimize.prototype.addHandle = function(length, callback) { this._queue.push({ length: length, callback: callback }); this._process(); }; ImgOptimize.prototype.end = function(data, encoding) { data && this.write(data, encoding); this.writable = false; }; module.exports = ImgOptimize;