Encoding 如何在NodeJS中编码/解码字符集编码?

Encoding 如何在NodeJS中编码/解码字符集编码?,encoding,utf-8,character-encoding,node.js,Encoding,Utf 8,Character Encoding,Node.js,我有以下代码: request({ url: 'http://www.myurl.com/' }, function(error, response, html) { if (!error && response.statusCode == 200) { console.log($('title', html).text()); } }); 但是Im爬行的网站可能有不同的字符集(utf8、iso-8859-1等)。如何获取并始终按照正确的编码(utf8)对htm

我有以下代码:

request({ url: 'http://www.myurl.com/' }, function(error, response, html) {
  if (!error && response.statusCode == 200) {
    console.log($('title', html).text());
  }
});
但是Im爬行的网站可能有不同的字符集(utf8、iso-8859-1等)。如何获取并始终按照正确的编码(utf8)对html进行编码/解码


感谢并抱歉我的英语;)

首先,您可以发送一个Accept字符集头,这将阻止网站在其他字符集中发送数据

一旦得到响应,就可以检查字符集条目的Content-Type头并进行适当的处理


当内容编码未知时,另一种黑客(我过去使用过)是尝试使用所有可能的内容编码进行解码,并坚持使用不会引发异常的编码(尽管在python中使用)。

网站可以在返回的HTML中返回内容类型头中的内容编码或内容类型元标记,例如:

<meta http-equiv="Content-Type" content="text/html; charset=latin1"/>

我知道我可以对请求使用
编码
选项,但问题是我还不知道页面的字符集(我知道标题或元标记),您也可以尝试此页面上宣布的模块:下面是directi链接:
request({url: 'http://www.myurl.com/', encoding: 'binary'}, function(error, response, html) {
    enc = charset(response.headers, html)
    enc = enc or jchardet.detect(html).encoding.toLowerCase()
    if enc != 'utf-8'
        iconv = new Iconv(enc, 'UTF-8//TRANSLIT//IGNORE')
        html = iconv.convert(new Buffer(html, 'binary')).toString('utf-8')
    console.log($('title', html).text());
});