Node.js 编码不是 UTF-8

Node.js encoding not UTF-8

我阅读了 html 编码为 win1251 的页面。但我无法渲染它,因为它向我显示了错误的编码符号。使用 utf8 此代码工作正常。我怎样才能阅读和显示不是utf8?谢谢

var charset = require('charset');
var iconv = require('iconv-lite');
var router = express.Router();


// accept POST request on the homepage
router.post('/', function (req, res) {

  request(req.body.url, function (error, response, body) {

    var result = [];
    if (error || response.statusCode != 200) {
        console.log(error);

    } else {
        console.log(charset(response.headers, body));
        var enc = charset(response.headers, body);
        if (enc != 'utf-8') {

            body = iconv.decode(body, 'win1251');
            console.log(body);
        }
        var $ = cheerio.load(body);

        //get title
        result.push("Title-> " + $("title").text());

如果您在 request() 选项中设置 encoding: nullbody 将是 Buffer 而不是 UTF-8 字符串。这将使您能够正确地将编码转换为 UTF-8。

示例:

request({url: req.body.url, encoding: null}, function (error, response, body) {

如果 body 的编码最终是 UTF-8,你可以简单地这样做:

body = body.toString('utf8');

如果有人也遇到这个问题。我做了而不是(这也很好)

body = body.toString('utf8');

我的代码

var iconv = require('iconv-lite');
.......................

body = iconv.decode(body, 'win1251');