node.js fs.readFile 中的编码被忽略

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15772925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:05:05  来源:igfitidea点击:

encoding is ignored in fs.readFile

node.js

提问by Micha Roon

I am trying to read the contents of a properties file in node. this is my call:

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

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

The console prints a buffer:

控制台打印一个缓冲区:

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

when I replace the code with this:

当我用这个替换代码时:

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

it works fine. But the node documentationsays the String is converted to utf8 if the encoding is passed in the options

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

the output of node --version is v0.10.2

node --version 的输出是 v0.10.2

What am I missing here?

我在这里缺少什么?

thank you for your support

感谢您的支持

回答by Jonathan Lonowski

Depending on the version of Node you're running, the argument may be just the encoding:

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

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

The 2nd argument changed to optionswith v0.10:

第二个参数更改为optionsv0.10

  • FS readFile(), writeFile(), appendFile()and their Sync counterparts now take an optionsobject (but the old API, an encodingstring, is still supported)
  • FS readFile()writeFile()appendFile()和他们同行同步,现在需要一个options对象(但旧的API,一个encoding字符串,仍然支持)

For former documentation:

对于以前的文档:

回答by youssouf

You should change {encoding: 'utf8'}to {encoding: 'utf-8'}, for example:

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

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