为什么Node.js的fs.readFile()返回一个缓冲区而不是字符串? [英] Why does Node.js' fs.readFile() return a buffer instead of string?
问题描述
我试图读取 test.txt
(它位于Javascript源文件的同一个文件夹中)的内容,并使用下面的代码显示它:
var fs = require(fs);
fs.readFile(test.txt,function(err,data){
if(err)throw err;
console.log(data);
});
nano
:
$ b
测试Node.js readFile()
我得到这个:
$ p $ 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 $
从文档:
如果未指定编码,则返回原始缓冲区。
这可能解释< Buffer ...>
。指定一个有效的编码,例如 utf-8
作为文件名后的第二个参数。例如,
fs.readFile(test.txt,utf8,function(err,data){.. 。});
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);
});
The content of the test.txt
was created on nano
:
Testing 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$
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,
fs.readFile("test.txt", "utf8", function(err, data) {...});
这篇关于为什么Node.js的fs.readFile()返回一个缓冲区而不是字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!