http.get()解读

上源码

exports.get = function(options, cb) {
var req = exports.request(options, cb);
req.end();
return req;
};

//get 本质上是简化的 request, 没有body 自带了request.end()

exports.request = function(options, cb) {
return new ClientRequest(options, cb);
};

request调用的ClientRequest的instance

const client = require('_http_client');
const ClientRequest = exports.ClientRequest = client.ClientRequest;

//ClientRequest is coming from module _http_client
client.ClientRequest 具体看源码, options里主要检查是否给了domain protocol port method agent 等参数。

对于重点解决的cb – callback 如下

if (cb) {
self.once('response', cb);
}

once 是event中定义的

//doc解释

Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed.

EventEmitter.prototype.once = function once(type, listener) {
if (typeof listener !== 'function')
throw new TypeError('listener must be a function');

var fired = false;

function g() {
this.removeListener(type, g);

if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}

g.listener = listener;
this.on(type, g);

return this;
};

//once 主要对cb是不是function判断然后 主要是一次执行的逻辑判断, 后面调用 on

EventEmitter.prototype.on = EventEmitter.prototype.addListener;

//继续addListener
重点code

existing = events[type];

判断 response 是 可以找到的event类型

if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] = [existing, listener];
}

并变为array类型

后续如何触发event未跟踪到