EN
TypeScript - atob / btoa functions equivalents in Node.js
3 points
In this article, we would like to show you atob and btoa functions equivalents in TypeSrcipt in Node.js.
Note:
In the presented solution, we use the Buffer class, which is in a global scope in Node.js and does not need to be imported using the
require()
function.The only thing you need to do is to install Node.js types for development using:
xxxxxxxxxx
1npm i --save-dev @types/node
In web browser JavaScript btoa()
function is used to convert binary to Base64-encoded ASCII string. btoa
function name should be read as "binary to ASCII".
xxxxxxxxxx
1
const toBase64 = (text: string): string => {
2
return Buffer.from(text, 'binary').toString('base64');
3
};
4
5
console.log(toBase64('This is text...')); // VGhpcyBpcyB0ZXh0Li4u
Output:
xxxxxxxxxx
1
VGhpcyBpcyB0ZXh0Li4u
In web browser JavaScript atob()
function is used to convert Base64-encoded ASCII string to binary. atob
function name should be read as "ASCII to binary".
xxxxxxxxxx
1
const toBinary = (base64: string): string => {
2
return Buffer.from(base64, 'base64').toString('binary');
3
};
4
5
console.log(toBinary('VGhpcyBpcyB0ZXh0Li4u')); // This is text...
Output:
xxxxxxxxxx
1
This is text...