在这种情况下,方法克隆会起作用吗?

时间:2012-07-09 20:38:09

标签: node.js

我正在尝试构建一个调试代理,以便在调用各种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

1 个答案:

答案 0 :(得分: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()。

这样的东西

还有一件事,您可能更愿意将此函数从原型赋值更改为普通方法(将函数传递给克隆)这可能会使您的设计更加清晰。