将文件编码为base 64 Nodej

vx6bjr1n  于 2022-11-29  发布在  Node.js
关注(0)|答案(3)|浏览(181)

我使用下面的代码将文件编码为base64。

var bitmap = fs.readFileSync(file);
return new Buffer(bitmap).toString('base64');

我发现文件中的“”‘’字符存在问题,但"字符没有问题
当我们有It’s时,节点对字符进行编码,但当我解码时,我看到的是It’s
下面是我用来解码的javascript:

fs.writeFile(reportPath, body.buffer, {encoding: 'base64'}

因此,一旦文件被编码和解码,它就变得无法使用这些时髦的字符-It’s
有人能解释一下吗?

bf1o4zei

bf1o4zei1#

这应该可以工作。示例脚本:

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如果未指定charset,则内容类型text/使用ISO-8859-1。

mfuanj7w

mfuanj7w2#

下面是一些有用的代码。

var bitmap = fs.readFileSync(file);

// Remove the non-standard characters
var tmp  = bitmap.toString().replace(/[“”‘’]/g,'');

// Create a buffer from the string and return the results
return new Buffer(tmp).toString('base64');
nnt7mjpx

nnt7mjpx3#

您可以为readFileSync函数本身提供base64编码。

const fileDataBase64 = fs.readFileSync(filePath, 'base64')

相关问题