javascript node.js toString 编码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16965281/
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-10-27 06:37:21  来源:igfitidea点击:

node.js toString encoding

javascriptnode.jsencodingtostring

提问by igor

I have file encoded with koi8-u

我有用 koi8-u 编码的文件

I need to just copy this file, but, through toString()

我只需要复制这个文件,但是,通过 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)
})

I tried iconv it back using different charsets but with no success. Thanks!

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

回答by TheHippo

You need to write and read everything with binaryencoding:

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

There should be two ways to do this:

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

Read data as Buffer:

读取数据为Buffer

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


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

Read data as binary encoded string:

以二进制编码读取数据string

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

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