Node.js - btoa is not defined error

0 points
Asked by:

I tried to encode text to base64 using btoa function in Node.js, but I get this error: 

const base64Data = btoa(data);
ReferenceError: btoa is not defined

My code: 

const data = 'password';
const base64Data = btoa(data);

How to solve it? Is there no btoa method in Node.js?

1 answer
0 points
Answered by:

Unfortunately, Node.js does not support this method. The solution, however, is to use the Buffer class, so you can use:

const btoa = (text) => {
    return Buffer.from(text, 'binary').toString('base64');

console.log(btoa('This is text...')); // VGhpcyBpcyB0ZXh0Li4u

Check out this article:

Node.js - atob / btoa functions equivalents

0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂