react / react-0.13.3 / examples / basic-commonjs / node_modules / browserify / node_modules / http-browserify / lib / response.js
80724 viewsvar Stream = require('stream');1var util = require('util');23var Response = module.exports = function (res) {4this.offset = 0;5this.readable = true;6};78util.inherits(Response, Stream);910var capable = {11streaming : true,12status2 : true13};1415function parseHeaders (res) {16var lines = res.getAllResponseHeaders().split(/\r?\n/);17var headers = {};18for (var i = 0; i < lines.length; i++) {19var line = lines[i];20if (line === '') continue;2122var m = line.match(/^([^:]+):\s*(.*)/);23if (m) {24var key = m[1].toLowerCase(), value = m[2];2526if (headers[key] !== undefined) {2728if (isArray(headers[key])) {29headers[key].push(value);30}31else {32headers[key] = [ headers[key], value ];33}34}35else {36headers[key] = value;37}38}39else {40headers[line] = true;41}42}43return headers;44}4546Response.prototype.getResponse = function (xhr) {47var respType = String(xhr.responseType).toLowerCase();48if (respType === 'blob') return xhr.responseBlob || xhr.response;49if (respType === 'arraybuffer') return xhr.response;50return xhr.responseText;51}5253Response.prototype.getHeader = function (key) {54return this.headers[key.toLowerCase()];55};5657Response.prototype.handle = function (res) {58if (res.readyState === 2 && capable.status2) {59try {60this.statusCode = res.status;61this.headers = parseHeaders(res);62}63catch (err) {64capable.status2 = false;65}6667if (capable.status2) {68this.emit('ready');69}70}71else if (capable.streaming && res.readyState === 3) {72try {73if (!this.statusCode) {74this.statusCode = res.status;75this.headers = parseHeaders(res);76this.emit('ready');77}78}79catch (err) {}8081try {82this._emitData(res);83}84catch (err) {85capable.streaming = false;86}87}88else if (res.readyState === 4) {89if (!this.statusCode) {90this.statusCode = res.status;91this.emit('ready');92}93this._emitData(res);9495if (res.error) {96this.emit('error', this.getResponse(res));97}98else this.emit('end');99100this.emit('close');101}102};103104Response.prototype._emitData = function (res) {105var respBody = this.getResponse(res);106if (respBody.toString().match(/ArrayBuffer/)) {107this.emit('data', new Uint8Array(respBody, this.offset));108this.offset = respBody.byteLength;109return;110}111if (respBody.length > this.offset) {112this.emit('data', respBody.slice(this.offset));113this.offset = respBody.length;114}115};116117var isArray = Array.isArray || function (xs) {118return Object.prototype.toString.call(xs) === '[object Array]';119};120121122