2014-09-02 46 views
5

我試圖訪問使用請求模塊的非UTF-8網站。此請求的回覆亂碼。Node.js mikeal /請求模塊 - 亂碼非UTF8網站(Shift_JIS)

var request = require('request'); 
request('http://www.alc.co.jp/', function (error, response, body) { 
    if (!error && response.statusCode == 200) { 
    console.log(body) // Print the web page. 
    } 
}); 

即使將編碼選項設置爲Shift_JIS,我也會看到亂碼的日文文本。

+1

https://github.com/ashtuchkin/iconv-lite我想你可以用它來SHIFT_JIS解碼緩衝區轉換爲UTF-8字符串。 – Jerry 2015-03-29 08:13:18

+0

在這裏找到另一個節點。我將嘗試將其製作成流星包。 https://github.com/polygonplanet/encoding.js – 2015-03-29 09:20:26

+0

也看起來不錯@Jerry – 2015-03-29 09:21:36

回答

4

你需要自己做轉換。下面的示例代碼使用node-iconv。

var Iconv = require('iconv').Iconv; 
    var request = require('request'); 
    request({ 
     uri: 'http://www.jalan.net/', 
     encoding: null, 
    }, function (error, response, body) { 
     if (!error && response.statusCode == 200) { 
     body = new Iconv('shift_jis', 'utf-8').convert(body).toString(); 
     console.log(body); // Print the web page. 
     } 
    }); 
  1. encoding: null參數詢問request不將Buffer(一個字節數組)轉換成String尚未。
  2. 我們將此緩衝區傳遞給Iconv以轉換爲UTF-8編碼的另一個Buffer
  3. 現在這個Buffer很適合被轉換成字符串。

(順便說一句,http://www.alc.co.jp已經切換到UTF-8,所以我取代與其他站點。)

+0

謝謝艾倫!這應該有助於一些人。乾杯! – 2015-04-05 11:47:21