| 1 | module.exports = Base64Decode; |
| 2 | |
| 3 | var Transform = require('stream').Transform || require('readable-stream').Transform; |
| 4 | require('util').inherits(Base64Decode, Transform); |
| 5 | |
| 6 | /** |
| 7 | * Decodes a Base64 data stream, coming in as a string or Buffer of UTF-8 text, into binary Buffers. |
| 8 | * @returns {Base64Decode} |
| 9 | * @constructor |
| 10 | */ |
| 11 | function Base64Decode() { |
| 12 | if ( !(this instanceof Base64Decode) ) |
| 13 | return new Base64Decode(); |
| 14 | |
| 15 | Transform.call(this, { |
| 16 | // The input is converted to strings, so no need to transform input strings to buffers |
| 17 | decodeStrings : false |
| 18 | }); |
| 19 | |
| 20 | // Any extra chars from the last chunk |
| 21 | this.extra = ''; |
| 22 | } |
| 23 | |
| 24 | /** |
| 25 | * Decodes a Base64 data stream, coming in as a string or Buffer of UTF-8 text, into binary Buffers. |
| 26 | * @param {Buffer|string} chunk |
| 27 | * @param encoding |
| 28 | * @param cb |
| 29 | * @private |
| 30 | */ |
| 31 | Base64Decode.prototype._transform = function (chunk, encoding, cb) { |
| 32 | // Convert chunk to a string |
| 33 | chunk = '' + chunk; |
| 34 | |
| 35 | // Add previous extra and remove any newline characters |
| 36 | chunk = this.extra + chunk.replace(/(\r\n|\n|\r)/gm, ''); |
| 37 | |
| 38 | // 4 characters represent 3 bytes, so we can only decode in groups of 4 chars |
| 39 | var remaining = chunk.length % 4; |
| 40 | |
| 41 | // Store the extra chars for later |
| 42 | this.extra = chunk.slice(chunk.length - remaining); |
| 43 | chunk = chunk.slice(0, chunk.length - remaining); |
| 44 | |
| 45 | // Create the new buffer and push |
| 46 | var buf = new Buffer(chunk, 'base64'); |
| 47 | this.push(buf); |
| 48 | cb(); |
| 49 | }; |
| 50 | |
| 51 | /** |
| 52 | * Emits 1, 2, or 3 extra characters of base64 data. |
| 53 | * @param cb |
| 54 | * @private |
| 55 | */ |
| 56 | Base64Decode.prototype._flush = function (cb) { |
| 57 | if ( this.extra.length ) |
| 58 | this.push(new Buffer(this.extra, 'base64')); |
| 59 | |
| 60 | cb(); |
| 61 | }; |