我有一个Windows-1255(希伯来语)编码的文件,我希望能够在Node.js中访问它。

我尝试使用fs.readFile打开文件,它给了我一个我无能为力的Buffer。我尝试将编码设置为Windows-1255,但是无法识别。

我还 checkout 了 windows-1255 package,但是我无法对其进行解码,因为fs.readFile要么给出Buffer要么给出UTF8字符串,并且该软件包需要1255编码的字符串。

如何在Node.js中读取Windows-1255编码的文件?

最佳答案

似乎使用node-iconv包是最好的方法。不幸的是,更容易包含在您的代码中的iconv-lite似乎并未实现CP1255的转码。

This thread & answer显示了简单的示例,并简要演示了如何使用这两个模块。

回到iconv,我在使用npm前缀的debian上安装时遇到了一些问题,我向维护者here提交了一个问题。我设法解决了安装时出现的问题,而“sudo chown”使我回到了已安装的模块。

我已经测试了可以访问的各种win-xxxx编码和CodePage((西欧+东欧示例))。

但是尽管CP1255以其受支持的编码列出,但我无法使其与CP1255一起使用,因为我没有在本地安装该特定的代码页,并且它全部被弄乱了。我尝试从this page窃取一些希伯来语脚本,但粘贴的版本始终被损坏。我不敢在我的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默认情况下返回 buffer
// 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
});

或者
// 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
});

关于javascript - 如何在Node.js中打开Windows-1255编码的文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26626581/

10-09 21:00