【问题标题】:Trying to understanding node createServer callback试图理解节点 createServer 回调
【发布时间】:2013-04-06 09:39:27
【问题描述】:

使用 Node.js hello world 示例:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

我试图找到 http.js 中的 createServer “查找”函数的位置,然后将两个对象传递给它(上面分别命名为 'req' 和 'res'。我搜索了 http.js 和我唯一发现的是:

exports.createServer = function(requestListener) {
  return new Server(requestListener);
};

这是否意味着匿名函数:

function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}

...作为“requestListener”传递并且...

return new Server(requestListener);

...req 和 res 对象是从哪里传回来的?

【问题讨论】:

  • 实际上requestListener 在服务器对象上发出“请求”事件时被调用。查看.emit('request'line 2017 of http.js 附近的位置
  • @Dan D. 那么这是否意味着当服务器收到请求时,emit 会将 req 和 res 传递给匿名函数?
  • 是的,通过 EventEmitter 模式。与在服务器构造函数中一样,它具有this.addListener('request', requestListener);,其中.emit 在内部路由.emit('request', req, res); .emit 在这种情况下使用事件的侦听器列表'request',并等效于使用传递的参数调用侦听器。
  • @JohnGalt,另一个问题,回调中的 req 和 res 究竟是什么类型。我在文档中找不到它们
  • 嗨 jason,req 和 res 或者只是对象...要查看它们包含的所有内容,只需记录它们 console.log(req)。

标签: node.js


【解决方案1】:

是的。在 Javascript 中,函数本身就是“值”,您可以分配给“对象”。既然你可以将一个对象传递给另一个函数,那么你可以将一个函数本身作为一个对象传递。

requestListener 是名为requestListener 的参数createServer,用于调用Server constructor

您也可以在 ruby​​ 中看到这一点,您可以在其中调用一个函数,同时将要在 do 块中执行的代码作为参数传递给它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-11
    • 2019-02-12
    相关资源
    最近更新 更多