time 函数将一个键值对添加到 Console 对象的 _times 属性中,它定义了 label 和由 process.hrtime 获取的当前时间戳之间的关系。
Console.prototype.time = function time(label = 'default') {
// Coerces everything other than Symbol to a string
label = `${label}`;
this._times.set(label, process.hrtime());
};
timeEnd 取回 time 函数存储的开始时间戳,并计算自该时间以来已经过去的时间量。
Console.prototype.timeEnd = function timeEnd(label = 'default') {
// Coerces everything other than Symbol to a string
label = `${label}`;
const time = this._times.get(label);
if (!time) {
process.emitWarning(`No such label'${label}'for console.timeEnd()`);
return;
}
const duration = process.hrtime(time);
const ms = duration[0] * 1000 + duration[1] / 1e6;
this.log('%s: %sms', label, ms.toFixed(3));
this._times.delete(label);
};
Console.prototype.count = function count(label = 'default') {
// Ensures that label is a string, and only things that can be// coerced to strings. e.g. Symbol is not allowedlabel = `${label}`;
const counts = this[kCounts];
let count = counts.get(label);
if (count === undefined)
count = 1;
elsecount++;
counts.set(label, count);
this.log(`${label}: ${count}`);
};
// Not yet defined by the https://console.spec.whatwg.org, but// proposed to be added and currently implemented by Edge. Having// the ability to reset counters is important to help prevent// the counter from being a memory leak.
如上所述,console API的规范没有明确定义重置标签计数的函数。考虑到标准定义了与 time 函数关联的 timeEnd 函数的规范,我认为这很有趣。无论如何,这个标准是一个活的标准,所以有足够的时间来增加它。
System Preferences → Network → Advanced → Proxies → Web Proxy (HTTP)
Settings → Network & Internet → Proxy
All Settings → Network → Network Proxy
如果要在单个终端捕获流量使用
export http_proxy=http://localhost:8008
。捕获加密流量(HTTPS)需要额外的步骤,请参阅本文档获取说明。
console
API 公开的大部分方法都利用了write
函数。例如,经常使用的log
函数看起来像这样。warn
函数看起来有点像这样。对于我来说,
console
API 里有一些方法比较新鲜。例如,time
和timeEnd
方法用来测量代码当中两点之间的时间差。例如,我们可以测试执行两条语句之间经过了多少时间,如下所示。time
函数将一个键值对添加到Console
对象的_times
属性中,它定义了label
和由process.hrtime
获取的当前时间戳之间的关系。timeEnd
取回time
函数存储的开始时间戳,并计算自该时间以来已经过去的时间量。结合使用
time
和timeEnd
函数可以很好地对代码片段进行性能测试。阅读代码库时引起我注意的另一组函数是
count
和countReset
函数。这些函数用于维护给定的特定label
的计数。count
函数增加或重置为特定label
定义的计数器,该计数器存储在Console
对象的kCounts
属性中。resetCount
函数重置特定label
的计数。在
countReset
函数上面写有一个有趣的注释。如上所述,console API的规范没有明确定义重置标签计数的函数。考虑到标准定义了与
time
函数关联的timeEnd
函数的规范,我认为这很有趣。无论如何,这个标准是一个活的标准,所以有足够的时间来增加它。就是这样!
Console
对象并不像其他一些函数那样复杂,但我在阅读代码时发现了一些新的用途。