4

node的入门就会写这样几行简单的代码,而createServer的过程究竟发生什么

const http = require('http');
const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(() => {
  console.log(`Server is running `);
});

问题1:request和response是什么

首先在http.js代码中

const Server = exports.Server = server.Server;

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

createServer做的事情很简单,只是new一个Server的实例,传入回调函数,并返回server

const server = require('_http_server');可以看到server来自_http_server

function Server(requestListener) {
  if (!(this instanceof Server)) return new Server(requestListener);
  net.Server.call(this, { allowHalfOpen: true });
  if (requestListener) {
    this.addListener('request', requestListener);
  }
  this.httpAllowHalfOpen = false;
  this.addListener('connection', connectionListener);
  this.timeout = 2 * 60 * 1000;
  this._pendingResponseData = 0;
}
util.inherits(Server, net.Server);

Server.prototype.setTimeout = function(msecs, callback) {
  this.timeout = msecs;
  if (callback)
    this.on('timeout', callback);
  return this;
};

exports.Server = Server;

Server继承net.Server,且requestListener,作为'request'事件的监听器。

在resOnFinish函数中,self.emit('request', req, res);触发了request事件。

  • res的来源
    var res = new ServerResponse(req);

  • req的来源

    • req来自parserOnIncoming的形参;
      parser.onIncoming = parserOnIncoming.bind(undefined, this, socket, state);而parser来自_http_common的parsers.alloc()。

    • 在方法parserOnHeadersComplete中skipBody = parser.onIncoming(parser.incoming, shouldKeepAlive);传入了request,
      parser.incoming = new IncomingMessage(parser.socket);说明传入的request是IncomingMessage的实例

    • IncomingMessage = require('_http_incoming').IncomingMessage;
      _http_incoming中可以看到util.inherits(IncomingMessage, Stream.Readable);所以IncomingMessage是继承自Stream.Readable

问题2:什么时候执行回调函数

  • connectionListener中有parser.onIncoming = parserOnIncoming.bind(undefined, this, socket, state);

  • 在server的初始化时

    • this.on('request', requestListener);注册request时加上执行回调操作

    • this.on('connection', connectionListener);注册connection的Listener

  • parserOnIncoming方法中 server.emit('request', req, res);发出request;最后在parserOnHeadersComplete方法中调用onIncoming,也就是server里的parserOnIncoming

  • 那么什么时候会发出connection操作呢?

    • 在net.js中的onconnection方法中self.emit('connection', socket);

    • _listen2方法中this._handle.onconnection = onconnection;

    • 在listen里调用listen2self._listen2(address, port, addressType, backlog, fd);

    • Server.prototype.listen = function() 中有对listen方法的调用,也就是说,当server调用listen,会出发connectionListener,进一步触发parserOnIncoming,发出request和response,触发requestListener也就是传入的回调函数


小帆
19 声望2 粉丝