Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js throws "btoa is not defined" error

Tags:

node.js

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?

like image 991
Joey Avatar asked Apr 16 '14 02:04

Joey


People also ask

What can I use instead of BTOA?

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.

Why is BTOA deprecated?

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.

What is BTOA?

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).


2 Answers

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.

like image 126
mscdex Avatar answered Sep 19 '22 17:09

mscdex


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:

like image 45
Iván Alegre Avatar answered Sep 18 '22 17:09

Iván Alegre