gpt4 book ai didi

javascript - 为什么 Node.js 的 fs.readFile() 返回缓冲区而不是字符串?

转载 作者:太空宇宙 更新时间:2023-11-04 01:47:07 25 4
gpt4 key购买 nike

我正在尝试读取 test.txt 的内容(位于 Javascript 源代码的同一文件夹中)并使用以下代码显示它:

var fs = require("fs");

fs.readFile("test.txt", function (err, data) {
if (err) throw err;
console.log(data);
});

test.txt 的内容是在 nano 上创建的:

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$

最佳答案

来自the docs:

If no encoding is specified, then the raw buffer is returned.

这可以解释 <Buffer ...> 。指定有效的编码,例如 utf-8 ,作为文件名之后的第二个参数。比如,

fs.readFile("test.txt", "utf8", function(err, data) {...});

关于javascript - 为什么 Node.js 的 fs.readFile() 返回缓冲区而不是字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51025098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com