24

我正在尝试读取节点中属性文件的内容。这是我的电话:

fs.readFile("server/config.properties", {encoding: 'utf8'}, function(err, data ) {
   console.log( data );
});

控制台打印一个缓冲区:

<Buffer 74 69 74 69 20 3d 20 74 6f 74 6f 0a 74 61 74 61 20 3d 20 74 75 74 75>

当我用这个替换代码时:

fs.readFile("server/config.properties", function(err, data ) {
   console.log( data.toString('utf8') );
});

它工作正常。但是节点文档说如果在选项中传递编码,则字符串将转换为 utf8

node --version 的输出是 v0.10.2

我在这里想念什么?

谢谢您的支持

4

2 回答 2

41

根据您运行的 Node 版本,参数可能只是encoding

fs.readFile("server/config.properties", 'utf8', function(err, data ) {
   console.log( data );
});

第二个参数更改为options v0.10

  • FS readFile(), writeFile(),appendFile()和它们的 Sync 对应物现在接受一个options对象(但encoding仍然支持旧的 API,一个字符串)

对于以前的文档:

于 2013-04-02T20:29:47.387 回答
8

您应该更改{encoding: 'utf8'}为 {encoding: 'utf-8'},例如:

fs.readFile("server/config.properties", {encoding: 'utf-8'}, function(err, data ) {
console.log( data );
});
于 2014-11-18T10:02:47.123 回答