Sci*_*ter 6 javascript character-encoding hebrew fs node.js
我有一个Windows-1255(希伯来语)编码的文件,我希望能够在Node.js中访问它.
我尝试打开文件fs.readFile,它给了我一个Buffer我无法做任何事情.我尝试将编码设置为Windows-1255,但是无法识别.
我也检查了windows-1255包,但我无法解码,因为fs.readFile要么给出一个Buffer或一个UTF8字符串,并且包需要一个1255编码的字符串.
如何读取Windows-1255Node.js中的-encoded文件?
似乎使用node-iconv包是最好的方法.不幸的是,更容易包含在代码中的iconv-lite似乎没有实现CP1255的转码.
这个主题和答案显示了简单的例子,并简明地演示了使用这两个模块.
回到iconv,我在使用npm前缀的debian上安装时遇到了一些问题,我在这里向维护者提交了一个问题.我设法解决了安装问题,以及"sudo chown" - 回到我安装的模块.
我已经测试了各种win-xxxx编码和可访问(西欧+东欧样本)的CodePages.
但我无法使用CP1255,尽管它列在他们支持的编码中,因为我没有在本地安装那个特定的代码页,而且它全部被破坏了.我试图从这个页面窃取一些希伯来语脚本,但粘贴的版本总是被破坏.我不敢在我的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')));
Run Code Online (Sandbox Code Playgroud)
处理文件编码的额外(非主题)解释,以及如何通过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
});
Run Code Online (Sandbox Code Playgroud)
要么
// 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
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4028 次 |
| 最近记录: |