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

查看:867
本文介绍了为什么Node.js的fs.readFile()返回一个缓冲区而不是字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  var fs = require(fs); 

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

test.txt 的内容是创建于 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆