EN
Node.js - atob / btoa functions equivalents
4 points
In this short article, we would like to present equivalents for btoa()
and atob()
functions under Node.js.
Quick solutions:
xxxxxxxxxx
1
const btoa = (text) => Buffer.from(text, 'binary').toString('base64');
xxxxxxxxxx
1
const atob = (base64) => Buffer.from(base64, 'base64').toString('binary');
btoa()
and atob()
are common JavaScript functions, but they are not available under Node.js, so it is necessary to use some equivalents.
"btoa" should be read as "binary to ASCII". btoa()
function converts binary to Base64-encoded ASCII string.
xxxxxxxxxx
1
const btoa = (text) => {
2
const buffer = Buffer.from(text, 'binary');
3
return buffer.toString('base64');
4
};
5
6
7
// Usage example:
8
9
console.log(btoa('This is text...')); // VGhpcyBpcyB0ZXh0Li4u
"atob" should be read as "ASCII to binary". atob()
function converts Base64-encoded ASCII string to binary.
xxxxxxxxxx
1
const atob = (base64) => {
2
const buffer = Buffer.from(base64, 'base64');
3
return buffer.toString('binary');
4
};
5
6
7
// Usage example:
8
9
console.log(atob('VGhpcyBpcyB0ZXh0Li4u')); // This is text...