javascript - 如何在 Node.js 中打开 Windows-1255 编码文件?

标签 javascript node.js character-encoding hebrew fs

我有一个 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 缓冲区读取文件的额外(题外话)解释:

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/

相关文章:

node.js - Nodejs中的mqtt文件传输? (使用 mqtt.js)

java - 当我分配 char (从文字或其他方式)时, "java internal encoding is UTF16"在这里意味着什么? char是以什么编码存储的?

java.nio.charset.IllegalCharsetNameException : 'ISO-8859-1'

javascript - jquery 创建变量并使用它来加载 - laravel

Javascript 未定义但存在公式

node.js - Sails.js:如何在 Bootstrap 中使用 i18n

sql-server - Unicode 到非 Unicode 转换

javascript - 使用 CDATA 替换 < 是否正确

javascript - history.pushState 和 location.hash 有什么区别?

javascript - js async/await 在使用此关键字时抛出错误