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