为什么 Node.js 的 fs.readFile() 返回一个缓冲区而不是字符串? [英] Why does Node.js' fs.readFile() return a buffer instead of string?
本文介绍了为什么 Node.js 的 fs.readFile() 返回一个缓冲区而不是字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试读取 test.txt
的内容(位于 Javascript 源的同一文件夹中)并使用以下代码显示它:
I'm trying to read the content of test.txt
(which is on the same folder of the Javascript source) and display it using this code:
var fs = require("fs");
fs.readFile("test.txt", function (err, data) {
if (err) throw err;
console.log(data);
});
test.txt
的内容是在 nano
上创建的:
The content of the test.txt
was created on nano
:
测试 Node.js readFile()
Testing Node.js readFile()
我明白了:
Nathan-Camposs-MacBook-Pro:node_test Nathan$ node main.js
<Buffer 54 65 73 74 69 6e 67 20 4e 6f 64 65 2e 6a 73 20 72 65 61 64 46 69 6c 65 28 29>
Nathan-Camposs-MacBook-Pro:node_test Nathan$
推荐答案
来自 文档:
如果未指定编码,则返回原始缓冲区.
If no encoding is specified, then the raw buffer is returned.
这可以解释
.指定有效的编码,例如 utf-8
,作为文件名后的第二个参数.比如,
Which might explain the <Buffer ...>
. Specify a valid encoding, for example utf-8
, as your second parameter after the filename. Such as,
fs.readFile("test.txt", "utf8", function(err, data) {...});
这篇关于为什么 Node.js 的 fs.readFile() 返回一个缓冲区而不是字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文