节点js中这种输出背后的原因是什么?

What is the reason behind this kind of output in node js?

Nodejs 输出显示了一些 Buffer 值,对于以下代码:

'use strict'

var fs;
fs = require("fs");

const output = fs.readFileSync('note.text');
console.log(output);

输出:

<Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64 0d 0a 73 68 61 67 65 65 73 68 61 0d 0a 73 6c 6c 69 74 0d 0a>

您正在读取文件流并打印流,而不是文本表示。您在流中数据的十六进制表示形式中看到的打印内容

hello world
shageesha
sllit
'use strict'

var fs;
fs = require("fs");

output = fs.readFileSync('note.text');
output = output.toString('utf8');
console.log(output);

readFile 函数读作 Buffer/Stream,您必须将其转换为可读形式。

如果指定了编码选项那么这个函数returns一个字符串。否则它 returns 一个缓冲区。

fs.readFileSync(path[, options])

像这样:

var fs = require('fs');
const output = fs.readFileSync('note.text', 'utf8');
console.log(output);

目前Node.js支持的字符编码包括:

'ascii' - 仅适用于 7 位 ASCII 数据。这种编码速度很快,如果设置,将去除高位。

'utf8' - 多字节编码的 Unicode 字符。许多网页和其他文档格式使用 UTF-8。

'utf16le' - 2 或 4 个字节,little-endian 编码的 Unicode 字符。支持代理对(U+10000 到 U+10FFFF)。

'ucs2' - 'utf16le'.

的别名

'base64' - Base64 编码。从字符串创建缓冲区时,此编码也将正确接受 RFC4648 第 5 节中指定的 "URL and Filename Safe Alphabet"。

'latin1' - 一种将缓冲区编码为 one-byte 编码字符串的方法(由 IANA 在 RFC1345 中定义,第 63 页,作为 Latin-1 补充块和 C0/C1控制代码)。

'binary' - 'latin1'.

的别名

'hex' - 将每个字节编码为两个十六进制字符。