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:
const btoa = (text) => Buffer.from(text, 'binary').toString('base64');
const atob = (base64) => Buffer.from(base64, 'base64').toString('binary');
Practical example
btoa()
and atob()
are common JavaScript functions, but they are not available under Node.js, so it is necessary to use some equivalents.
btoa()
function equivalent
"btoa" should be read as "binary to ASCII". btoa()
function converts binary to Base64-encoded ASCII string.
const btoa = (text) => {
const buffer = Buffer.from(text, 'binary');
return buffer.toString('base64');
};
// Usage example:
console.log(btoa('This is text...')); // VGhpcyBpcyB0ZXh0Li4u
atob()
function equivalent
"atob" should be read as "ASCII to binary". atob()
function converts Base64-encoded ASCII string to binary.
const atob = (base64) => {
const buffer = Buffer.from(base64, 'base64');
return buffer.toString('binary');
};
// Usage example:
console.log(atob('VGhpcyBpcyB0ZXh0Li4u')); // This is text...