Node中console.log的同步实现

console.log相信使用过js的朋友都不会陌生,对于我这种前端转过来的node开发者,用起这个函数更是毫不手软,使用它把需要的信息打印到标准输出,觉得就是1+1=2那么正常,但是有天在网上看到一个问题console.log到底是异步还是同步?我觉得很诧异,这还是个问题么?当然是同步啦。但是问题的答案出乎我的意料,上面告诉我是要分情况的,根据process.stdout的情况可能会出现异步的情况。我当时眉头一皱,才发现问题确实不是我想的那么简单,于是在Node的文档中发现了这一段提示:

Writes may be synchronous depending on what the stream is connected to and whether the system is Windows or POSIX:
	Files: synchronous on Windows and POSIX
	TTYs (Terminals): asynchronous on Windows, synchronous on POSIX
	Pipes (and sockets): synchronous on Windows, asynchronous on POSIX

当我发现自己对这个知识存在盲区后,赶紧深入内核去看看到底是啥情况,我选择了最常用的POSIX上的TTYs来深入理解。

从console.log出发

首先我在node源文件中从lib/console.js找到了console.log的代码:

Console.prototype.log = function log(...args) {
 write(this._ignoreErrors,
 this._stdout,
 util.format.apply(null, args),
 this._stdoutErrorHandler,
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值