In my node.js application I did an 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 defined.
Did I not do the install properly? What did I overlook?
js. If you're trying to use btoa in Node, you'll notice that it is deprecated. It'll suggest you to use the Buffer class instead.
btoa(): accepts a string where each character represents an 8bit byte. If you pass a string containing characters that cannot be represented in 8 bits, it will probably break. Probably that's why btoa is deprecated.
The btoa() method creates a Base64-encoded ASCII string from a binary string (i.e., a string in which each character in the string is treated as a byte of binary data).
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(Buffer.from('Hello World!').toString('base64'));
Reverse (assuming the content you're decoding is a utf8 string):
console.log(Buffer.from(b64Encoded, 'base64').toString());
Note: prior to Node v4, use new Buffer
rather than Buffer.from
.
The solutions posted here don't work in non-ascii characters (i.e. if you plan to exchange base64 between Node.js and a browser). In order to make it work you have to mark the input text as 'binary'.
Buffer.from('Hélló wórld!!', 'binary').toString('base64')
This gives you SOlsbPMgd/NybGQhIQ==
. If you make atob('SOlsbPMgd/NybGQhIQ==')
in a browser it will decode it in the right way. It will do it right also in Node.js via:
Buffer.from('SOlsbPMgd/NybGQhIQ==', 'base64').toString('binary')
If you don't do the "binary part", you will decode wrongly the special chars.
I got it from the implementation of the btoa npm package:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With