2012-07-09 77 views
0

我正在嘗試構建一個調試代理,以便在調用各種AP​​I時可以看到請求和響應,但是我堅持要將數據發送到original method在這種情況下,方法克隆會起作用嗎?

我怎樣才能發送塊到原來的方法?

var httpProxy = require('http-proxy'); 

var write2; 

function write (chunk, encoding) { 

    /* 
     error: Object #<Object> has no method '_implicitHeader' 
     because write2 is not a clone. 
    */ 
    //write2(chunk, encoding); 

    if (Buffer.isBuffer(chunk)) { 
     console.log(chunk.toString(encoding)); 
    } 
} 


var server = httpProxy.createServer(function (req, res, proxy) { 

    // copy .write 
    write2 = res.write; 
    // monkey-patch .write 
    res.write = write; 

    proxy.proxyRequest(req, res, { 
     host: req.headers.host, 
     port: 80 
    }); 

}); 

server.listen(8000); 

我的項目是here

回答

0

稍微修改JavaScript: clone a function

Function.prototype.clone = function() { 
    var that = this; 
    var temp = function temporary() { return that.apply(this, arguments); }; 
    for(key in this) { 
     Object.defineProperty(temp,key,{ 
      get: function(){ 
      return that[key]; 
      }, 
      set: function(value){ 
      that[key] = value; 
      } 
     }); 
    } 
    return temp; 
}; 

我已經改變了克隆分配,而使用getter和setter方法,以確保克隆的功能性的任何變化都會反映在克隆的對象上。

現在你可以使用類似於write2 = res.write.clone()的東西。

還有一件事,你可能更希望將此功能從原型分配更改爲常規方法(將函數傳遞給克隆)這可能會使您的設計稍微更清晰。

相關問題