【问题标题】:encoding is ignored in fs.readFile编码在 fs.readFile 中被忽略
【发布时间】:2014-11-18 18:56:34
【问题描述】:

我正在尝试读取 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

node--version的输出是v0.10.2

我在这里错过了什么?

感谢您的支持

【问题讨论】:

  • 两种方式都适合我。您可能使用的是旧版本的节点?我正在使用 v0.10.1

标签: node.js


【解决方案1】:

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

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

第二个参数改为optionswith v0.10

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

对于以前的文档:

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    猜你喜欢
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多