【问题标题】:node.js toString encodingnode.js toString 编码
【发布时间】:2013-06-02 15:35:41
【问题描述】:

我有用 koi8-u 编码的文件

我只需要复制这个文件,但是,通过 toString()

fs = require('fs')
fs.readFile('fileOne',function(e,data){
    data = data.toString() // now encoding is damaged

    ???  // my code must be here

    fs.writeFile('fileTwo',data)
})

我尝试使用不同的字符集返回 iconv 但没有成功。谢谢!

【问题讨论】:

  • 确保使用与阅读相同的编码进行书写。
  • @TheHippo ,如果我在读写两者中添加“utf8”或“ascii”编码,我会得到相同的结果,并且那里没有 koi8 的编码;(
  • 你试过binary吗?为什么需要字符串?这不能用Bufferstreams 完成吗?
  • @TheHippo 谢谢!我尝试了 writeFile 和 toString 的二进制文件,它解决了我的问题,所以你可以将它作为答案发布,我会接受它

标签: javascript node.js encoding tostring


【解决方案1】:

您需要使用binary 编码来编写和读取所有内容:

应该有两种方法可以做到这一点:

读取数据为Buffer:

fs = require('fs')
fs.readFile('fileOne', function(e, data){
    // data is a buffer
    buffer = data.toString('binary')


    fs.writeFile('fileTwo', {
        'encoding': 'binary'
    }, buffer);
});

将数据读取为二进制编码string:

fs = require('fs')
fs.readFile('fileOne', {
        'encoding': 'binary'
    }, function(e, data){
        // data is a string

        fs.writeFile('fileTwo', {
            'encoding': 'binary'
        }, data);
});

【讨论】:

    猜你喜欢
    • 2017-04-07
    • 1970-01-01
    • 2012-09-29
    • 2014-03-04
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 2015-11-06
    • 2014-06-07
    相关资源
    最近更新 更多