Aerodynamika
Aerodynamika

Reputation: 8413

Convert buffer base64 -> utf8 encoding node.js

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

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

 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.

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!

Upvotes: 16

Views: 34437

Answers (2)

jabclab
jabclab

Reputation: 15062

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

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

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

Upvotes: 26

mido
mido

Reputation: 25054

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

a simple example might be:

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

Upvotes: 38

Related Questions