Making the HTTP response a full-fledged Readable stream.

This commit is contained in:
ali.ibrahim 2016-10-06 14:14:05 +02:00
parent dcffb51e5e
commit 42bae9d71d
2 changed files with 30 additions and 3 deletions

View file

@ -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) {