node系列之console

地址

传送门

说明

该模块提供一系列类似于浏览器的调试输出功能。下面是简单的用法。

console.log('hello world'); 
// Prints: hello world, to stdout
console.log('hello %s', 'world'); 
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened')); 
// Prints: [Error: Whoops, something bad happened], to stderrconst name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`); 
// Prints: Danger Will Robinson! Danger!, to stderr

Console类

Console: require('console').Console
或者
Console: console.Console
因为console是全局对象,所以用不用require都是一样的。

  • new Console(stdout[, stderr])
const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');// custom simple logger
const logger = new Console(output, errorOutput);// use it like console
var count = 5;
logger.log('count: %d', count);// in stdout.log: count 5

用起来还是挺像一般的console的。

  • console.assert(value[, message][, ...args])
    console居然还有断言。和assert的用法基本一致

打印日志

  • console.error([data][, ...args])
  • console.warn([data][, ...args]) console.error的别名
  • console.log([data][, ...args])
  • console.info([data][, ...args]) console.log的别名
    上面三种用法差不多。

时间差

  • console.time(label)
  • console.timeEnd(label)
    只要保持label一致,就能打印时间差
console.time('100-elements');
for (var i = 0; i < 100; i++) {
     ;
}
console.timeEnd('100-elements');
// output : 100-elements: 0.104ms

这个用法还是挺好的。不用自己再手动去生成一个开始时间和结束时间就能直接计算了。

错误追踪

  • console.trace(message[, ...args])
    直接在某个地方抛出异常,提供程序错误定位功能。

小结

很容易和著名的log4js联系在一起。也可以用这个模块实现一套自己的日志系统。当然,在开发和测试中都是不推荐直接使用console的。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,292评论 19 139
  • Console 稳定性:2-Stable 0x01 你真的了解Node.js的console吗 Console模块...
    小菜荔枝阅读 6,169评论 0 3
  • 第1章 小试牛刀 $ 是普通用户,# 表示管理员用户 root。 shebang:#!。sharp / hash ...
    巴喬書摘阅读 11,495评论 1 4
  • https://nodejs.org/api/documentation.html 工具模块 Assert 测试 ...
    KeKeMars阅读 11,495评论 0 6
  • 踏上站台那一刻,身上每个毛管都在舒张,雀跃得像个孩子。 好久不见,我回来了。 心心念念回家,为的是家里的味道 ...
    倔强二叔阅读 1,794评论 0 0