diff --git a/lib/node-http-proxy/http-proxy.js b/lib/node-http-proxy/http-proxy.js index a391102..bf3c297 100644 --- a/lib/node-http-proxy/http-proxy.js +++ b/lib/node-http-proxy/http-proxy.js @@ -218,46 +218,24 @@ HttpProxy.prototype.proxyRequest = function (req, res, buffer) { return; } - // - // For each data `chunk` received from the `reverseProxy` - // `response` write it to the outgoing `res`. - // If the res socket has been killed already, then write() - // will throw. Nevertheless, try our best to end it nicely. - // - var paused = false; - response.on('data', function (chunk) { - if (req.method !== 'HEAD' && res.writable) { - try { - var flushed = res.write(chunk); - } - catch (ex) { - console.error("res.write error: %s", ex.message); - - try { res.end() } - catch (ex) { console.error("res.end error: %s", ex.message) } - - return; - } - - if (!flushed && !paused) { - paused = true; - response.pause(); - res.once('drain', function () { - paused = false; - try { response.resume() } - catch (er) { console.error("response.resume error: %s", er.message) } - }); - - // - // Force the `drain` event in 100ms if it hasn't - // happened on its own. - // - setTimeout(function () { - res.emit('drain'); - }, 100); + + function ondata(chunk) { + if (res.writable) { + if (false === res.write(chunk) && response.pause) { + response.pause(); + } } } - }); + + response.on('data', ondata); + + function ondrain() { + if (response.readable && response.resume) { + response.resume(); + } + } + + res.on('drain', ondrain); // // When the `reverseProxy` `response` ends, end the