【问题标题】:nodejs http response encodingnodejs http响应编码
【发布时间】:2011-02-27 19:44:53
【问题描述】:

是否可以读取非 utf8 编码的网页?例如 windows-1251。 我尝试使用 node-iconv 转换结果:

var convertedBody = new Iconv('windows-1251','utf-8').convert(responseBody));

但我得到了例外:

Error: EILSEQ, Illegal character sequence.
    at IncomingMessage.<anonymous> (/root/nodejstest/test2.js:22:19)
    at IncomingMessage.emit (events.js:59:20)
    at HTTPParser.onMessageComplete (http.js:111:23)
    at Socket.ondata (http.js:1183:22)
    at Socket._onReadable (net.js:654:27)
    at IOWatcher.onReadable [as callback] (net.js:156:10)

谢谢!

【问题讨论】:

  • 您是否已经在 nodejs google 群组中查看了this thread?似乎针对您的问题...

标签: node.js iconv


【解决方案1】:

这是解决您问题的有效方法。您必须先使用 Buffer 并将您的字符串转换为二进制。

request({ 
uri: website_url,
method: 'GET',
encoding: 'binary'
}, function (error, response, body) {
    body = new Buffer(body, 'binary');
    conv = new iconv.Iconv('windows-1251', 'utf8');
    body = conv.convert(body).toString();
     }
});

【讨论】:

    【解决方案2】:

    看看iconv-lite 库。 使用它,您的代码可能如下所示:

    var iconv = require('iconv-lite');
    request(
        { 
            uri: website_url,
            method: 'GET',
            encoding: 'binary'
        },
        function(err, resp, body){
            body = iconv.decode(body, 'win1251');
        }
    );
    

    【讨论】:

      【解决方案3】:

      Iconv 没有 windows-1251

      您可以从bnoordhuis/node-iconv 验证编码列表。

      顺便说一句,来自维基百科:

      Windows-1251 和 KOI8-R(或其乌克兰变体 KOI8-U)比 ISO 8859-5 更常用。

      【讨论】:

        【解决方案4】:
        const request = require('request');
        const iconv = require('iconv-lite');
        
        request({
            url: 'http://meta.ua',
            encoding: 'binary',
        }, (err,res,body) => {
            if (err) throw err;
        
            var decoded = iconv.decode(res.body, 'win1251');
        
            console.log(decoded);
        });
        

        【讨论】:

        • 请不要发布裸代码,同时解释代码的作用。
        猜你喜欢
        • 2016-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多