node.js 将 Binary.toString('encode64') 转换回 Binary

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8305988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:49:38  来源:igfitidea点击:

Convert Binary.toString('encode64') back to Binary

node.jsencodingbinary-data

提问by ariefbayu

I've seen severaltutorialexplaining how to convert binary image into encode64 representations:

我看过几个教程,解释了如何将二进制图像转换为 encode64 表示:

var image = new Buffer(bl.toString(), 'binary').toString('base64');

My question is, how to return this string representation, back to it's buffer's binary data.

我的问题是,如何返回这个字符串表示,回到它的缓冲区的二进制数据。

回答by tillberg

This question has some helpful info: How to do Base64 encoding in node.js?

这个问题有一些有用的信息:How to do Base64 encoding in node.js?

The Buffer class itself does the conversion:

Buffer 类本身进行转换:

var base64data = Buffer.from('some binary data', 'binary').toString('base64');

console.log(base64data);
// ->  'c29tZSBiaW5hcnkgZGF0YQ=='

var originaldata = Buffer.from(base64data, 'base64');

console.log(originaldata);
// ->  <Buffer 73 6f 6d 65 20 62 69 6e 61 72 79 20 64 61 74 61>

console.log(originaldata.toString());
// ->  some binary data

回答by Tony Mack

new Bufferis deprecated

new Buffer已弃用

From Binary to base64:

从二进制到 base64:

const base64data = Buffer.from('some binary data', 'binary').toString('base64');
console.log(base64data);
// ->  'c29tZSBiaW5hcnkgZGF0YQ=='

From base64 to binary:

从 base64 到二进制:

 const origionalData = Buffer.from('some base64 data', 'base64') 

console.log(origionalData) 

// ->  'c29tZSBiaW5hcnkgZGF0YQ=='