node.js - 将文件编码为 base 64 Nodejs

标签 node.js encoding

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

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

我发现文件中的 “”‘’ 字符有问题,但 "

没问题

当我们有 It's 时, Node 对字符进行编码,但是当我解码时,我将其视为

这是我用来解码的 javascript:

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

因此,一旦文件被编码和解码,它就无法使用这些古怪的字符 - It's

任何人都可以阐明这一点吗?

最佳答案

这应该有效。 示例脚本:

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 text/使用 ISO-8859-1。

关于node.js - 将文件编码为 base 64 Nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44763464/

相关文章:

javascript - SOAP-Request 可与 PHP 一起使用,但与 NodeJS 一起抛出语法错误

node.js - 在 node.js 上使用 aes-ecb 加密二进制数据

PHP urlencode - 仅对文件名进行编码并且不要触摸斜杠

ruby - ActionMailer 字符串编码

node.js - 使用 NodeJS 实例化一个 Admin SDK 目录服务对象

node.js - Sequelize 将多个查询数据发送到页面

javascript - 打印 jade 文件中的变量

python:下载和缓存 XML 文件 - 如何处理编码声明?

php - 蛋糕PHP : How to save Arabic words into mysql table?

android - 从 Android 将图像上传到 tumblr API