2017-06-26 37 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');