Node 抓取非utf-8编码页面

代码示例 Nodejs抓取非utf8字符编码的页面 -- Ruby's Louvre

var http = require('http');
var iconv = require('iconv-lite');
var url=require('url');
 
var html = "";
var getURL = url.parse('http://bj.soufun.com/');
var req =http.get(getURL, function (res) {
    res.setEncoding('binary');//or hex
    res.on('data',function (data) {//加载数据,一般会执行多次
        html += data;
    }).on('end', function () {
            var buf=new Buffer(html,'binary');//这一步不可省略
            var str=iconv.decode(buf, 'GBK');//将GBK编码的字符转换成utf8的
            console.log(str);
        })
}).on('error', function(err) {
        console.log("http get error:",err);
    });

UTF8与GBK进行转换,可以把Unicode作为中间编码。
UTF8编解Unicode规则简单,参见 UTF8
GBK编解Unicode无特定规则,一般可通过查表方式
GBK兼容ascii码,ascii字符用一字节编码,最高位为0,其它字符用两位编码,高字节从0x81。编解码时通过此规律对单字节和双字节字符加以区分。
由此可见,GBK是单字节、双字节变长编码。
理解了上面几点后,编解码GBK文件其实只需要一个GBK–>Unicode的码表就够了。
GBK编码时,通过Unicdoe–>GBK,生成相应的GBK字节流;
GBK解码时,通过GBK–>Unicode,生成UCS2字节流,再通过buffer.toString(‘UCS2’)即可转换成string对象。

// npm install iconv-lite
var iconv = require('iconv-lite');
var str = iconv.decode(buf, 'GBK'); //return unicode string from GBK encoded bytes
var buf = iconv.encode(str, 'GBK');//return GBK encoded bytes from unicode string
原文地址:https://www.cnblogs.com/flowerszhong/p/6731250.html