From 42bae9d71d1f69d0a8d4e794a8f08d1984854982 Mon Sep 17 00:00:00 2001 From: "ali.ibrahim" Date: Thu, 6 Oct 2016 14:14:05 +0200 Subject: [PATCH] Making the HTTP response a full-fledged Readable stream. --- atom/browser/api/atom_api_url_request.cc | 4 ++-- lib/browser/api/net.js | 29 +++++++++++++++++++++++- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/atom/browser/api/atom_api_url_request.cc b/atom/browser/api/atom_api_url_request.cc index c1c95e27e56d..e3d0f5992969 100644 --- a/atom/browser/api/atom_api_url_request.cc +++ b/atom/browser/api/atom_api_url_request.cc @@ -368,7 +368,7 @@ void URLRequest::OnResponseData( if (!buffer || !buffer->data() || !buffer->size()) { return; } - EmitResponseEvent(false, "data", buffer); + Emit("data", buffer); } void URLRequest::OnResponseCompleted() { @@ -381,7 +381,7 @@ void URLRequest::OnResponseCompleted() { return; } response_state_.SetFlag(ResponseStateFlags::kEnded); - EmitResponseEvent(false, "end"); + Emit("end"); Close(); } diff --git a/lib/browser/api/net.js b/lib/browser/api/net.js index 5f2c7345d4a3..d00946be8376 100644 --- a/lib/browser/api/net.js +++ b/lib/browser/api/net.js @@ -3,6 +3,7 @@ const url = require('url') const {EventEmitter} = require('events') const util = require('util') +const Readable = require('stream').Readable const binding = process.atomBinding('net') const {net, Net} = binding const {URLRequest} = net @@ -14,10 +15,20 @@ let kSupportedProtocols = new Set() kSupportedProtocols.add('http:') kSupportedProtocols.add('https:') -class IncomingMessage extends EventEmitter { +class IncomingMessage extends Readable { constructor (urlRequest) { super() this._url_request = urlRequest + this._shouldPush = false; + this._data = []; + this._url_request.on('data', (event, chunk) => { + this._storeInternalData(chunk) + this._pushInternalData() + }) + this._url_request.on('end', () => { + this._storeInternalData(null) + this._pushInternalData() + }) } get statusCode () { @@ -48,6 +59,22 @@ class IncomingMessage extends EventEmitter { return this._url_request.rawResponseHeaders } + _storeInternalData(chunk) { + this._data.push(chunk) + } + + _pushInternalData() { + while (this._shouldPush && this._data.length > 0) { + const chunk = this._data.shift() + this._shouldPush = this.push(chunk) + } + } + + _read() { + this._shouldPush = true + this._pushInternalData() + } + } URLRequest.prototype._emitRequestEvent = function (async, ...rest) {