2017-05-22 245 views
0

我用get的方法獲取外部網站的內容request模塊。如果外部網站的編碼是UTF-8,這是確定的,但它顯示錯誤與其他編碼,如移JISNodejs獲取外部網站內容時的錯誤編碼

function getExternalUrl(request, response, url){ 

    mod_request.get(url, function (err, res, body) { 
    //mod_request.get({uri: url, encoding: 'binary'}, function (err, res, body) { 
     if (err){ 
      console.log("\terr=" + err); 
     }else{ 
      var result = res.body; 
      // Process res.body 
      response.write(result); 
     } 
     response.end(); 
    }); 
} 

我怎樣才能用正確的編碼外部網站的內容?

回答

0

我發現的方法來做到:

  1. 獲取與binary編碼

    變種mod_request =需要( '請求');
    mod_request.get({uri:url,encoding:'binary',headers:headers},function(err,res,body){});

  2. 創建Bufferbinary格式

    變種contentBuffer =新緩衝液(res.body, '二進制');

  3. 通過detect-character-encoding NPM獲取頁的真實編碼

    變種mod_detect_character_encoding =要求( '檢測字符編碼');
    var charsetMatch = mod_detect_character_encoding(contentBuffer);

  4. 轉換頁面utf-8iconv NPM

    變種mod_iconv =要求( '的iconv')語言Iconv。
    var iconv = new mod_iconv(charsetMatch.encoding,'utf-8');
    var result = iconv.convert(contentBuffer).toString();

P/S:This way is only applied for text file (html, css, js). Please do not apply for image file or others which is not text