是否可以读取非utf8编码的网页?例如windows-1251.我尝试使用node-iconv转换结果:
var convertedBody = new Iconv('windows-1251','utf-8').convert(responseBody));
Run Code Online (Sandbox Code Playgroud)
但我得到例外:
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)
Run Code Online (Sandbox Code Playgroud)
谢谢!
这是解决您问题的方法.您必须先使用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();
}
});
Run Code Online (Sandbox Code Playgroud)