看来使用节点 iconv https://github.com/bnoordhuis/node-iconv包是最好的方式。很遗憾iconv-lite https://github.com/ashtuchkin/iconv-lite更容易包含在您的代码中似乎没有实现 CP1255 的转码。
此主题及答案 https://stackoverflow.com/a/14551669/3239869显示了简单的示例并简洁地演示了这两个模块的使用。
回到 iconv,我在使用 npm 前缀的 debian 上安装时遇到了一些问题,我向维护者提交了一个问题here https://github.com/bnoordhuis/node-iconv/issues/101。我设法解决了这个问题 sudo-ing 安装,并“sudo chown”-ing 返回给我已安装的模块。
我已经测试了可以访问(西欧+东欧样本)的各种 win-xxxx 编码和代码页。
但我无法让它与 CP1255 一起工作,尽管它列在他们支持的编码中,因为我没有在本地安装特定的代码页,并且它全部被破坏了。我试图从那里窃取一些希伯来语脚本这一页 http://www.i18nguy.com/unicode/shma.html,但粘贴的版本总是损坏的。我不敢在我的 Windows 机器上实际安装该语言,因为担心我不会把它变砖 - 抱歉。
// sample.js
var Iconv = require('iconv').Iconv;
var fs = require('fs');
function decode(content) {
var iconv = new Iconv('CP1255', 'UTF-8//TRANSLIT//IGNORE');
var buffer = iconv.convert(content);
return buffer.toString('utf8');
};
console.log(decode(fs.readFileSync('sample.txt')));
关于处理文件编码以及如何通过 Node.js 缓冲区读取文件的额外(偏离主题)解释:
fs.readFile http://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback返回一个buffer http://nodejs.org/api/buffer.html默认情况下。
// force the data to be string with the second optional argument
fs.readFile(file, {encoding:'utf8'}, function(error, string) {
console.log('raw string:', string);// autoconvert to a native string
});
OR
// use the raw return buffer and do bitwise processing on the encoded bytestream
fs.readFile(file, function(error, buffer) {
console.log(buffer.toString('utf8'));// process the binary buffer
});