Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

javascript - 为什么Node.js的fs.readFile()返回缓冲区而不是字符串?(Why does Node.js' fs.readFile() return a buffer instead of string?)

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$ 
  ask by Nathan Campos translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the docs:

(从文档:)

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

(如果未指定编码,则返回原始缓冲区。)

Which might explain the <Buffer ...> .

(也许可以解释<Buffer ...> 。)

Specify a valid encoding, for example utf-8 , as your second parameter after the filename.

(指定一个有效的编码,例如utf-8 ,作为文件名之后的第二个参数。)

Such as,

(如,)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...