Javascript 为什么 Node.js 的 fs.readFile() 返回一个缓冲区而不是字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6456864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does Node.js' fs.readFile() return a buffer instead of string?
提问by Nathan Campos
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:
我正在尝试读取test.txt
(位于 Javascript 源的同一文件夹中)的内容并使用以下代码显示它:
var fs = require("fs");
fs.readFile("test.txt", function (err, data) {
if (err) throw err;
console.log(data);
});
The content of the test.txt
was created on nano
:
的内容test.txt
创建于nano
:
Testing Node.js readFile()
测试 Node.js readFile()
And I'm getting this:
我得到了这个:
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$
回答by davin
From the docs:
从文档:
If no encoding is specified, then the raw buffer is returned.
如果未指定编码,则返回原始缓冲区。
Which might explain the <Buffer ...>
. Specify a valid encoding, for example utf-8
, as your second parameter after the filename. Such as,
这可能解释了<Buffer ...>
. 指定有效的编码,例如utf-8
,作为文件名后的第二个参数。如,
fs.readFile("test.txt", "utf8", function(err, data) {...});
回答by hvgotcodes
try
尝试
fs.readFile("test.txt", "utf8", function(err, data) {...});
basically you need to specify the encoding.
基本上你需要指定编码。
回答by Loilo
This comes up high on Google, so I'd like to add some contextual information about the original question (emphasis mine):
这在谷歌上很受欢迎,所以我想添加一些关于原始问题的上下文信息(强调我的):
Whydoes Node.js' fs.readFile() return a buffer instead of string?
为什么Node.js 的 fs.readFile() 返回一个缓冲区而不是字符串?
Because files aren't always text
因为文件并不总是文本
Even if youas the programmer know it: Node has no idea what's in the file you're trying to read. It could be a text file, but it could just as well be a ZIP archive or a JPG image — Node doesn't know.
即使您作为程序员都知道:Node 不知道您要读取的文件中的内容。它可以是一个文本文件,但也可以是一个 ZIP 档案或 JPG 图像——Node 不知道。
Because reading text files is tricky
因为读取文本文件很棘手
Even if Node knewit were to read a text file, it still would have no idea which character encodingis used (i.e. how the bytes in the file map to human-readable characters), because the character encoding itself is not stored in the file.
即使 Node知道它要读取一个文本文件,它仍然不知道使用哪种字符编码(即文件中的字节如何映射到人类可读的字符),因为字符编码本身并不存储在文件中.
There are ways to guessthe character encoding of text files with more or less confidence (that's what text editors do when opening a file), but you usually don't want your code to rely on guesses without your explicit instruction.
有一些方法可以或多或少地有把握地猜测文本文件的字符编码(这是文本编辑器在打开文件时所做的事情),但是您通常不希望代码在没有明确指令的情况下依赖于猜测。
Buffers to the rescue!
缓冲器来救援!
So, because it does not and can not know all these details, Node just reads the file byte for byte, without assuming anything about its contents.
所以,因为它不知道也不能知道所有这些细节,Node 只是一个字节一个字节地读取文件,而不对其内容做任何假设。
And that's what the returned buffer is: an unopinionated container for raw binary content. How this content should be interpreted is up to you as the developer.
这就是返回的缓冲区:一个用于原始二进制内容的非独立容器。如何解释这些内容取决于您作为开发人员。
回答by Taro Alan
Async:
异步:
fs.readFile('test.txt', 'utf8', callback);
Sync:
同步:
var content = fs.readFileSync('test.txt', 'utf8');
回答by Andz
It is returning a Buffer object.
它正在返回一个 Buffer 对象。
If you want it in a string, you can convert it with data.toString()
:
如果你想把它放在一个字符串中,你可以用data.toString()
:
var fs = require("fs");
fs.readFile("test.txt", function (err, data) {
if (err) throw err;
console.log(data.toString());
});
回答by ayusha
The data
variable contains a Buffer
object. Convert it into ASCII encoding using the following syntax:
的data
变量包含一个Buffer
对象。使用以下语法将其转换为 ASCII 编码:
data.toString('ascii', 0, data.length)
Asynchronously:
异步:
fs.readFile('test.txt', 'utf8', function (error, data) {
if (error) throw error;
console.log(data.toString());
});