2015-10-06 80 views
0

我一直面臨node.js表達框架編碼/解碼風格的問題。 簡單的背景下,我存儲在MySQL數據庫的pdf文件與longblob數據類型與latin1字符集。從服務器端,我需要發送UTF8編碼格式的二進制數據,因爲我的客戶端只知道utf8解碼格式。 我嘗試了所有可能的解決方案在谷歌上。Node.js編碼UTF-8問題

例如: new Buffer(mySqlData).toString('utf8'); 已經嘗試使用給定功能的模塊「UTF8」utf8.encode(mySqlData);但它不起作用。

另外我已經嘗試過「base64」編碼,並在base64解碼的客戶端檢索數據。它工作得很好,但我需要有utf8編碼集。你也知道base64肯定會增加大小。

請幫幫忙。

+0

如何將二進制數據作爲utf-8發送? – Joe

回答

1

好的,你的問題是拉丁到utf-8的轉換。如果你只是打電話給你的buffer.toString('utf-8'),拉丁編碼的字符是錯誤的。

要將其他字符集轉換爲utf-8,簡單的使用方法是使用iconvicu-charset-detector。有了這個,你可以從所有可能的字符集切換到utf-8(除了特定的字符集)。

這是一個使用流轉換的例子。結果流使用UTF-8編碼:

var charsetDetector  = require("node-icu-charset-detector"), 
    Iconv    = require('iconv').Iconv, 
    Stream    = require('stream'), 

function convertToUtf8(source, callback) { 
    var iconv, 
     charsetTestStream = new Stream.PassThrough(), 
     newResStream  = new Stream.PassThrough(); 

    source.pipe(charsetTestStream); 
    source.pipe(newResStream); 

    charsetDetector.detectCharsetStream(charsetTestStream, function (charset) { 
     if (!iconv && charset && !/utf-*8/i.test(charset.toString())) { 
      try { 
       iconv = new Iconv(charset, 'utf-8'); 
       console.log('Converting from charset %s to utf-8', charset); 
       iconv.on('error', function (err) { 
        callback(err); 
       }); 

       var convertStream = newResStream.pipe(iconv); 
       callback(null, convertStream); 
      } catch(err) { 
       callback(err); 
      } 
      return; 
     } 
     callback(null, newResStream); 
    }); 
}