今天看了一个 npm 包的源码,里面用到了 process.stdout.write 这个 API 。咋一看感觉跟 Java 的 System.out.print 有点类似,但是 JS 打印的语句难道不是 console.log 么?于是查了下,发现 console.log 原来底层就是基于 process.stdout.write 实现的:
Console.prototype.log = function() {
this._stdout.write(util.format.apply(this, arguments) + '\n');
};
这边有两个注意点:
process.stdout.write
函数只接受字符串,如果传别的类型就会报错。而 console.log 可以接收任意类型,因为在输出前经过了 format 函数格式化;
可以参考 Node.js 官方文档:http://nodejs.cn/api/util.html#util_util_format_format_args
process.stdout.write
函数默认不会换行,而console.log
函数因为在最后拼接了一个换行符 \n ,导致每次输出都会换行;
在 npm 包源码中,因为不希望每次都换行,而是在一行内输出,因此用了 process.stdout.write