2017-06-26 42 views
0

我使用下面的代碼將文件編碼爲base64。 var bitmap = fs.readFileSync(file); return new Buffer(bitmap).toString('base64');將文件編碼爲base 64 Nodejs

我覺得在文件中我們有「」和「」字符的問題。 它的罰款「

,當我們有這是,它編碼字符和解碼時,我把它看作 伊達€™的

這裏是我的解碼代碼 - fs.writeFile( reportPath,body.buffer,{編碼: '的base64'}

因此,一旦該文件編碼和解碼,它變得無法使用這些時髦charaters - 伊達€™的

任何人都可以對此有所瞭解嗎?謝謝!

回答

1

這應該工作。 示例腳本:

const fs = require('fs') 
const filepath = './testfile' 
//write "it's" into the file 
fs.writeFileSync(filepath,"it's") 

//read the file 
const file_buffer = fs.readFileSync(filepath); 
//encode contents into base64 
const contents_in_base64 = file_buffer.toString('base64'); 
//write into a new file, specifying base64 as the encoding (decodes) 
fs.writeFileSync('./fileB64',contents_in_base64,{encoding:'base64'}) 
//file fileB64 should now contain "it's" 

我懷疑你的原始文件沒有UTF-8編碼,看你的解碼碼: fs.writeFile(reportPath, body.buffer, {encoding: 'base64'})

我猜你的內容來自於某些種類這麼一個HTTP請求內容可能不是utf-8編碼的。看看這個: https://www.w3.org/International/articles/http-charset/index如果沒有指定字符集Content-Type文本/使用ISO-8859-1。

+0

三江源。我必須首先刪除撇號(單和雙)的非標準ascii字符,然後編碼到64位。 – user3439399

0

這是幫助的代碼。

var bitmap = fs.readFileSync(file); 

//刪除非標準字符

var tmp = bitmap.toString().replace(/[「」‘’]/g,''); 

//從字符串用於指向我向右方向創建緩衝區

var bitmap1 = new Buffer(tmp); 
return bitmap1.toString('base64');