I have large Javascript objects which I would like to encode to base-64 for AWS Kinesis` It turns out that:

let objStr = new Buffer(JSON.stringify(obj), 'ascii');
new Buffer(objStr, 'base64').toString('ascii') !== objStr

I'm trying to keep this as simple as possible.

How can I base-64 encode JSON and safely decode it back to its original value?

推荐答案

You misunderstood the Buffer(str, [encoding]) constructor, the encoding tells the constructor what encoding was used to create str, or what encoding the constructor should use to decode str into a byte array.

Basically the Buffer class represents byte streams, it's only when you convert it from/to strings that encoding comes into context.

You should instead use buffer.toString("base64") to get base-64 encoded of the buffer content.

let objJsonStr = JSON.stringify(obj);
let objJsonB64 = Buffer.from(objJsonStr).toString("base64");

Node.js相关问答推荐

无法验证叶签名|无法验证第一个证书

try 使用Express和连接池将数据插入MySQL数据库时出现拒绝访问错误

无法从MongoDB文档中保存的对象数组中获取对象的属性

在函数上执行 toString 的Typescript 会产生奇怪的字符 (path_1, (0, Promise.writeFile))

Nestjs重写子类dto nodejs中的属性

我的 MERN 网站一直告诉我我的一个函数不是一个函数

我需要聚合两个 MongoDB 集合

如何配置 Nginx React 和 Express

使用正则表达式查找文档,但输入是数组

GridFS 大文件下载使 Node.js 服务器崩溃. MongoServerError:排序超出了字节的内存限制

如何在 Node.js 的 console.log() 中创建换行符

在Go中,编写非阻塞代码有意义吗?

Node_redis - 如何删除密钥?

运行摩卡+伊斯坦布尔+通天塔

NODEJS 进程信息

create-react-app,安装错误(找不到命令)

如何仅在丢失的路由上将 Express.js 设置为 404?

桌面应用程序仅支持 oauth_callback 值 'oob'/oauth/request_token

'node' 未被识别为内部或外部命令

promise 回调返回promise