console.log和process.stdout.write中的节点流缓冲区 [英] Node stream buffers in console.log vs process.stdout.write

查看:69
本文介绍了console.log和process.stdout.write中的节点流缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 NodeJS v5.6 ,我创建了一个名为 read-stream.js 的文件:

Using NodeJS v5.6 I created a file called read-stream.js:

const
    fs = require('fs'),
    stream = fs.createReadStream(process.argv[2]);

stream.on('data', function(chunk) {
    process.stdout.write(chunk);
});

stream.on('error', function(err) {
    process.stderr.write("ERROR: " + err.message + "\n");
});

和一个名为 target.txt

hello world
this is the second line 

如果我执行 node read-stream.js target.txt <$ c $的内容c> target.txt 可以正常打印在我的控制台上,一切都很好。

If I do node read-stream.js target.txt the contents of target.txt are printed normally on my console and all is well.

但是,如果我切换进程。 stdout.write(chunk); console.log(chunk); ,那么我得到的结果是:

However if I switch process.stdout.write(chunk); with console.log(chunk); then the result I get is this:

<Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64 0a 74 68 69 73 20 69 73 20 74 68 65 20 73 65 63 6f 6e 64 20 6c 69 6e 65 0a>

我最近发现通过执行 console.log(chunk.toString( )); 我的文件内容将再次正常打印。

I recently found out that by doing console.log(chunk.toString()); the contents of my file are once again printed normally.

根据此问题 console.log 应该使用 process.stdout.write ,外加 \n 字符。但是,这里的编码/解码究竟发生了什么?

As per this question, console.log is supposed to use process.stdout.write with the addition of a \n character. But what exactly is happening with encoding/decodings here?

预先感谢。

推荐答案

process.stdout 是一个流,其 write()函数仅接受字符串和缓冲区。 chunk 是一个Buffer对象, process.stdout.write 直接在控制台中写入数据字节,因此它们显示为字符串。 console.log 在输出之前创建Buffer对象的字符串表示形式,因此< Buffer 指示对象的类型,然后是该缓冲区的字节。

process.stdout is a stream and its write() function only accepts strings and buffers. chunk is a Buffer object, process.stdout.write writes the bytes of data directly in your console so they appear as strings. console.log builds a string representation of the Buffer object before outputting it, hence the <Buffer at the beginning to indicate the object's type and following are the bytes of this buffer.

在侧面, process.stdout 一个流,您可以直接通过管道传递给它,而不是读取每个块:

On a side note, process.stdout being a stream, you can pipe to it directly instead of reading every chunk:

stream.pipe(process.stdout);

这篇关于console.log和process.stdout.write中的节点流缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆