kst*_*tis 1 buffer character-encoding node.js
使用NodeJS v5.6我创建了一个名为的文件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");
});
Run Code Online (Sandbox Code Playgroud)
和一个纯文本的数据文件target.txt:
hello world
this is the second line
Run Code Online (Sandbox Code Playgroud)
如果我这样做node read-stream.js target.txt的内容target.txt正常在我的控制台打印,一切都很好.
但是,如果我切换process.stdout.write(chunk);,console.log(chunk);那么我得到的结果是:
<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>
Run Code Online (Sandbox Code Playgroud)
我最近发现通过做console.log(chunk.toString());我的文件的内容再次正常打印.
根据这个问题,console.log应该使用process.stdout.write添加一个\n字符.但是这里编码/解码究竟发生了什么?
提前致谢.
process.stdout是一个流,它的write()功能只接受字符串和缓冲区.chunk是一个Buffer对象,process.stdout.write直接在控制台中写入数据字节,使它们显示为字符串.console.log在输出之前构建Buffer对象的字符串表示,因此<Buffer在开头指示对象的类型,以下是此缓冲区的字节.
另外,process.stdout作为一个流,您可以直接管道而不是读取每个块:
stream.pipe(process.stdout);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6373 次 |
| 最近记录: |