node.js - nodejs http响应编码

标签 node.js iconv

是否可以阅读非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)

谢谢!

最佳答案

这是您问题的有效解决方案。您必须先使用 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();
     }
});

关于node.js - nodejs http响应编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5135450/

相关文章:

javascript - 无法读取未定义的属性“id”

node.js - Mongoose 按查找字段分组

node.js - Node JS - 当我想显示来自 Mongoose 的列表时异步

zend-framework - Zend_Pdf UTF-8 字符?

json - 如何在 mongodb 中展平子文档

javascript - 多次调用 google 表格时,API 身份验证不适用于第二次调用 : Request had insufficient authentication scopes

mysql - 在 mysql 中将字符集从 UTF-8 更改为 ISO-8859-1

php - 调试 iconv_strlen 错误 - PHP 5.5

unix - iconv 将大型机 EBCDIC 文件转换为 Unix 可读格式,将数据写入一行

php - 在 php 中将 UTF-16LE 转换为 UTF-8