node.js:如何以自定义格式获取和解码/编码响应

这是在node.js中支持哪些编码的页面: 在这里或这里 。 许多stream行的(或前段时间stream行的)编码都不见了,比如windows-1252。

我想获取一个在Windows-1252中的网页并parsing响应,最后将其保存到一个文件中。 编码有问题。 我已经做了很多不同的尝试,我的思想吹起来:(

所以我知道node.js中有iconviconv-lite模块,它们支持比node.js更多的编码。 我想使用iconv-lite ,因为我无法编译公司机器上iconv所需的东西。 无论如何,我有

 var iconv = require('iconv-lite'); 

现在,难以取得回应。 正如我写的,我的资源位于networking的某个地方,所以我需要发起一个HTTP请求。 我一直在尝试node-wget(npm: wget模块), http.requesthttp.get和所有这些尝试失败。

我也google了,最接近的解决scheme,我所需要的似乎是nodejs编码使用请求 / https://stackoverflow.com/a/22027928/769384 ,但作者并没有写在地狱的request是什么 – 这是一个节点模块? 他如何加载它?

我也读过https://groups.google.com/forum/#!topic/nodejs/smA6-jGq2pw ,但没有find干净的解决scheme。

我将不胜感激一小部分的代码,使我能够获取一个Web文档,并将其从windows-1252编码飞行转换为UTF-8 。 唯一的参数是文档的URL。

下面是一个使用iconv-litehttp的例子(我没有添加任何error handling,但只是给出了一个如何实现这样的想法):

 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); }); 

编辑 :只是注意到iconv-lite支持stream。 这是一个更小版本的retrieve()函数:

 function retrieve(url, callback) { http.get(url, function(res) { res.pipe(iconv.decodeStream('win1252')).collect(callback); }); }