duc*_*cin 3 javascript encoding node.js
该页面说明了node.js支持的编码:here或here。许多流行的(或一段时间前流行的)编码都丢失了,例如Windows-1252。
我想获取Windows-1252中的网页并解析响应,最后将其保存到文件中。我在编码时遇到问题。我已经做了很多不同的尝试,但我的头脑却发疯了:(
因此,我知道node.js中有iconv和iconv-lite模块比node.js支持更多的编码。我想使用iconv-lite,因为我无法iconv在公司机器上编译所需的内容。反正我有
var iconv = require('iconv-lite');
Run Code Online (Sandbox Code Playgroud)
现在,困难的部分-获取响应。如我所写,我的资源位于网络中的某个位置,因此我需要触发HTTP请求。我一直在试图节点的wget(NPM:wget模块)http.request,http.get并且所有这些尝试都失败了。
我也用谷歌搜索,最接近我需要的解决方案似乎是使用request / /sf/answers/1541954991/进行的nodejs编码,但是作者没有写出到底是request什么-它是一个节点模块?他如何加载它?
我还阅读了https://groups.google.com/forum/#!topic/nodejs/smA6-jGq2pw,但是那里没有干净的解决方案。
我希望能用最少的代码集来获取Web文档并将其即时地从windows-1252编码转换为UTF-8。唯一的参数是文档的URL。
这是一个使用iconv-liteand 的示例http(我没有添加任何错误处理,但是只是提供了有关如何实现类似内容的想法):
var http = require('http');
var iconv = require('iconv-lite');
function retrieve(url, callback) {
http.get(url, function(res) {
var chunks = [];
// Collect all the response chunks.
res.on('data', function(chunk) {
chunks.push(chunk);
});
// The response has been fully read here.
res.on('end', function() {
// Collect all the chunks into one buffer.
var buffer = Buffer.concat(chunks);
// Convert to a (UTF-8-encoded) string.
var str = iconv.decode(buffer, 'windows-1252');
// Call the callback with the string.
return callback(null, str);
});
});
}
// To use:
retrieve(YOUR_URL, function(err, html) {
console.log(html);
});
Run Code Online (Sandbox Code Playgroud)
编辑:刚刚注意到也iconv-lite支持流。这是该retrieve()函数的小得多的版本:
function retrieve(url, callback) {
http.get(url, function(res) {
res.pipe(iconv.decodeStream('win1252')).collect(callback);
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1850 次 |
| 最近记录: |