1

我一直在尝试将 utf8 字符串转换为 windows-1255 字符串。我想出了这段代码:

var fs = require('fs');
var Iconv = require('iconv').Iconv;
var iconvlite = require('iconv-lite');
var windows1255 = require('windows-1255');

/////////////////// Attempting to converted from utf-8 to windows-1255
function encode(content) {
  var iconv = new Iconv('UTF-8', 'CP1255//TRANSLIT//IGNORE');
  var buffer2 = iconv.convert(content);
  return buffer2;
  //return buffer.toString('ISO-88591-1');      // toString cannot convert in the encoding windows1255
};
var buffer3 = new Buffer(encode(fs.readFileSync('/home/USER/git/npm-test-1/utf8.txt')));
console.log(buffer3);
//str = iconvlite.decode(buffer3, 'win1255');
str = iconvlite.decode(buffer3, "1255");
console.log(str);


fs.writeFile("/home/USER/git/npm-test-1/windows-1255.txt", str, function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("The file was saved!");
}); 

唯一的问题是最后一步,当我尝试从缓冲区转换为字符串时。它可以将其转换为 utf8 编码字符串:|

  1. 这是一个错误吗?

  2. 有没有办法解决?我真的需要 windows-1255 字符串而不是缓冲区。

  3. 有人知道这样做的方法吗?
4

0 回答 0