Node.js连接createServer代码

时间:2014-05-13 08:48:57

标签: javascript node.js connect

我正在阅读Node.js Connect版本2.15.0:

/**
 * Create a new connect server.
 *
 * @return {Function}
 * @api public
 */

function createServer() {
  function app(req, res, next){ app.handle(req, res, next); }
  utils.merge(app, proto);
  utils.merge(app, EventEmitter.prototype);
  app.route = '/';
  app.stack = []; 
  for (var i = 0; i < arguments.length; ++i) {
    app.use(arguments[i]);
  }
  return app;
};

几个问题:

  1. app.handle似乎是在proto中提供的,因为有 proto.js中定义的app.handle。所以,这是一个闭包的用途, 而app.handle的定义不是在Node解析function app()时,而是在代码中解析?此外,app本身也已定义 in..uh .. function app()。代码对我来说很有趣。

  2. 何时调用function app()?所有我知道创建服务器创建     服务器。那么我何时会调用该函数以及如何调用?我     做类似的事情:

    app = createServer()
    app.listen(3000)
    app(req, res, next)
    
  3. utils.merge()只是说

    exports.merge = function(a, b){ 
      if (a && b) {
        for (var key in b) {
          a[key] = b[key];
        }   
      }
      return a;
    };
    

    这是一种常见的做法,而不是继承或什么?它看起来像mixin

1 个答案:

答案 0 :(得分:0)

  
      
  1. app.handle似乎是在proto中提供的,因为有   proto.js中定义的app.handle。所以,这是一个闭包的用途,   而app.handle的定义不是在Node解析function app()时   但后来在代码中?此外,app本身也已定义   in..uh .. function app()。代码对我来说很有趣。
  2.   

是的,app.handle来自proto。但是,不,在app函数内访问app不是闭包,在所有函数声明中,函数都可以通过其名称获得。

  

2。何时调用function app()?我所知道的createServer创造了所有      服务器。那么我何时会调用该函数以及如何调用?

connect docs使用此示例代码:

var app = connect();
…
http.createServer(app).listen(3000);

您可以看到connect(您发布的createServer函数)确实创建了app,它作为处理程序传递给实际的http服务器。

  

3。 utils.merge()是一种常见做法而不是继承或什么?它看起来像mixin

是的,merge确实将一个对象混合到另一个对象中。这样做是为了使用所有必要的方法扩展函数对象app。这是必要的,因为以标准方式Define a function with a prototype chain是不可能的。他们可能也沿着这些方向使用过某些东西:

app.__proto__ = utils.merge(Object.create(EventEmitter.prototype), proto);

但随后app将不再是instanceof Function;没有功能方法。