react / wstein / node_modules / jest-cli / node_modules / jsdom / node_modules / request / node_modules / stringstream / stringstream.js
81144 viewsvar util = require('util')1var Stream = require('stream')2var StringDecoder = require('string_decoder').StringDecoder34module.exports = StringStream5module.exports.AlignedStringDecoder = AlignedStringDecoder67function StringStream(from, to) {8if (!(this instanceof StringStream)) return new StringStream(from, to)910Stream.call(this)1112if (from == null) from = 'utf8'1314this.readable = this.writable = true15this.paused = false16this.toEncoding = (to == null ? from : to)17this.fromEncoding = (to == null ? '' : from)18this.decoder = new AlignedStringDecoder(this.toEncoding)19}20util.inherits(StringStream, Stream)2122StringStream.prototype.write = function(data) {23if (!this.writable) {24var err = new Error('stream not writable')25err.code = 'EPIPE'26this.emit('error', err)27return false28}29if (this.fromEncoding) {30if (Buffer.isBuffer(data)) data = data.toString()31data = new Buffer(data, this.fromEncoding)32}33var string = this.decoder.write(data)34if (string.length) this.emit('data', string)35return !this.paused36}3738StringStream.prototype.flush = function() {39if (this.decoder.flush) {40var string = this.decoder.flush()41if (string.length) this.emit('data', string)42}43}4445StringStream.prototype.end = function() {46if (!this.writable && !this.readable) return47this.flush()48this.emit('end')49this.writable = this.readable = false50this.destroy()51}5253StringStream.prototype.destroy = function() {54this.decoder = null55this.writable = this.readable = false56this.emit('close')57}5859StringStream.prototype.pause = function() {60this.paused = true61}6263StringStream.prototype.resume = function () {64if (this.paused) this.emit('drain')65this.paused = false66}6768function AlignedStringDecoder(encoding) {69StringDecoder.call(this, encoding)7071switch (this.encoding) {72case 'base64':73this.write = alignedWrite74this.alignedBuffer = new Buffer(3)75this.alignedBytes = 076break77}78}79util.inherits(AlignedStringDecoder, StringDecoder)8081AlignedStringDecoder.prototype.flush = function() {82if (!this.alignedBuffer || !this.alignedBytes) return ''83var leftover = this.alignedBuffer.toString(this.encoding, 0, this.alignedBytes)84this.alignedBytes = 085return leftover86}8788function alignedWrite(buffer) {89var rem = (this.alignedBytes + buffer.length) % this.alignedBuffer.length90if (!rem && !this.alignedBytes) return buffer.toString(this.encoding)9192var returnBuffer = new Buffer(this.alignedBytes + buffer.length - rem)9394this.alignedBuffer.copy(returnBuffer, 0, 0, this.alignedBytes)95buffer.copy(returnBuffer, this.alignedBytes, 0, buffer.length - rem)9697buffer.copy(this.alignedBuffer, 0, buffer.length - rem, buffer.length)98this.alignedBytes = rem99100return returnBuffer.toString(this.encoding)101}102103104