我有一个 Windows-1255(希伯来语)编码的文件,我希望能够在 Node.js 中访问它。
我尝试使用 fs.readFile
打开文件,它给了我一个我无法使用的 Buffer
。我尝试将编码设置为 Windows-1255
,但无法识别。
我还检查了 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 安装的问题,并且“sudo chown”返回给我安装的模块。
我已经测试了各种可以访问(西欧+东欧样本)的 win-xxxx 编码和代码页。
但我无法让它与 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 缓冲区读取文件的额外(题外话)解释:
// 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/