Joey Joey - 1 year ago 765
Node.js Question

Node.js - "btoa is not defined" error

In my node.js application I did a

npm install btoa-atob
so that I could use the btoa() and atob() functions which are native in client-side javascript but for some reason weren't included in node. The new directory showed up in my node_modules folder, which itself is in root alongside app.js. Then I made sure to add btoa-atob as a dependency in my package.json file which is in root.

However, for some reason it still will not work.

console.log(btoa("Hello World!"));

^ should output "SGVsbG8gV29ybGQh" to the console, but instead I get the error "btoa is not defiend."

Did I not do the install properly? What did I overlook?

Answer Source

The 'btoa-atob' module does not export a programmatic interface, it only provides command line utilities.

If you need to convert to Base64 you could do so using Buffer:

console.log(new Buffer('Hello World!').toString('base64'));

Reverse (assuming the content you're decoding is a utf8 string):

console.log(new Buffer(b64Encoded, 'base64').toString());