fs.readFile中忽略编码

时间:2013-04-02 19:41:15

标签: node.js

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

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') );
});

它工作正常。但node documentation表示如果在选项

中传递编码,则字符串将转换为utf8

节点--version的输出是v0.10.2

我在这里缺少什么?

感谢您的支持

2 个答案:

答案 0 :(得分:37)

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

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

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

  
      
  • FS readFile()writeFile()appendFile()及其同步对应方现在采用options对象(但旧API,encoding字符串仍为支持)
  •   

对于以前的文档:

答案 1 :(得分:5)

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

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