javascript 转换缓冲区 base64 -> utf8 编码 node.js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26721893/
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-10-28 06:22:57  来源:igfitidea点击:

Convert buffer base64 -> utf8 encoding node.js

javascriptnode.jsencodingutf-8base64

提问by Aerodynamika

My app imports all the messages from the Notes folder of GMail. I use imap npm module for that.

我的应用程序从 GMail 的 Notes 文件夹中导入所有邮件。我为此使用 imap npm 模块。

Using the example from their github page I get all the contents of a message into a buffer:

使用他们 github 页面中的示例,我将消息的所有内容放入缓冲区:

 stream.on('data', function(chunk) {
     count += chunk.length;
     buffer += chunk.toString('utf8');
 });

However, what I get are sentences like

然而,我得到的是这样的句子

  0KHQvdCw0YfQsNC70LAg0YHQvtC30LTQsNC10YLRgdGPINGA0LXRiNC10YLQutCwINC/0YDQvtGB 0YLRgNCw0L3RgdGC0LLQsCDQstC+0L7QsdGA0LDQttC10L3QuNGPLiZuYnNwOzxkaXY+PGJyPjwv ZGl2PjxkaXY+0JfQsNGC0LXQvCDQvdCwI

(wrong conversion from Russian)

(俄语转换错误)

I found out that these are the snippets of text encoded in base64 and in order to read them I need to convert it from base64 to utf8.

我发现这些是用 base64 编码的文本片段,为了阅读它们,我需要将其从 base64 转换为 utf8。

There is also sometimes an annoying = character that appears from nowhere...

有时也有一个烦人的 = 字符不知从哪里出现...

 letting them f= all on her shoulders

Do you know how I could get rid of those two problems?

你知道我怎样才能摆脱这两个问题吗?

Thank you!

谢谢!

回答by mido

new Buffer(...)has been deprecated for a while now, go for Buffer.from(...)

new Buffer(...)已经弃用一段时间了,继续 Buffer.from(...)

a simple example might be:

一个简单的例子可能是:

var utf8encoded = Buffer.from(base64encoded, 'base64').toString('utf8');

回答by jabclab

In order to convert from a base64 encoded Stringto utf8 you can use the following:

为了从 base64 编码转换String为 utf8,您可以使用以下命令:

var base64encoded = '0KHQvdCw0YfQsNC70LAg0YHQvtC30LTQsNC10YLRgdGPINGA0LXRiNC10YLQutCwINC/0YDQvtGB 0YLRgNCw0L3RgdGC0LLQsCDQstC+0L7QsdGA0LDQttC10L3QuNGPLiZuYnNwOzxkaXY+PGJyPjwv ZGl2PjxkaXY+0JfQsNGC0LXQvCDQvdCwI';

var utf8encoded = (new Buffer(base64encoded, 'base64')).toString('utf8');