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

我有这个代码:

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等)如何得到它和编码/解码的HTML总是正确的编码(UTF8)?

感谢和抱歉我的英语;)

该网站可以在返回的HTML内返回内容types标题或内容types元标记中的内容编码,例如:

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

您可以使用charset模块为您自动检查这两个。 不是所有的网站或服务器都会指定一个编码,所以你会想回到从数据本身检测字符集。 jschardet模块可以帮助你。

一旦你制定了字符集,你可以使用iconv模块来进行实际的转换。 这是一个完整的例子:

 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()); }); 

首先,您可以发送一个Accept-Charset标头,这将防止网站以其他字符集发送数据。

获得响应后,您可以检查字符集条目的Content-Type标题并进行适当的处​​理。

当内容编码未知时,Anothr hack(我曾经使用过)试图使用所有可能的内容编码进行解码,并坚持不抛出exception(使用python)。