EN
Node.js - Base64 encode and decode
0
points
In this article, we would like to show you how to encode and decode Base64 in JavaScript under Node.js.
Quick solution:
const text = 'some text...';
const encoded = Buffer.from(text, 'utf8').toString('base64');
console.log('Encoded text: ' + encoded); // c29tZSB0ZXh0Li4u
const decoded = Buffer.from(encoded, 'base64').toString('utf8');
console.log('Decoded text: ' + decoded); // some text...
1. Encode
In this example, we create a Base64-encoded ASCII string using Buffer.from()
with toString()
method.
const text = 'some text...';
const encoded = Buffer.from(text, 'utf8').toString('base64');
console.log('Encoded text: ' + encoded); // c29tZSB0ZXh0Li4u
Output:
c29tZSB0ZXh0Li4u
2. Decode
In this example, we decode a string of data that has been encoded using Base64 encoding.
const encoded = 'c29tZSB0ZXh0Li4u';
const decoded= Buffer.from(encoded, 'base64').toString('utf8');
console.log('Decoded text: ' + decoded); // some text...
Output:
some text...