Node.js抛出“未定义btoa".错误 [英] Node.js throws "btoa is not defined" error
问题描述
在我的node.js应用程序中,我做了一个npm install btoa-atob
,以便可以使用客户端javascript中固有的btoa()和atob()函数,但由于某些原因未包含在node中.新目录显示在我的node_modules文件夹中,该文件夹本身与app.js一起位于根目录中.然后,确保将btoa-atob作为依赖项添加到根目录下的package.json文件中.
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!"));
^应该向控制台输出"SGVsbG8gV29ybGQh",但是,我收到错误消息未定义btoa".
^ 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?
推荐答案
"btoa-atob"模块不导出编程接口,仅提供命令行实用程序.
The 'btoa-atob' module does not export a programmatic interface, it only provides command line utilities.
如果您需要转换为Base64,则可以使用Buffer:
If you need to convert to Base64 you could do so using Buffer:
console.log(Buffer.from('Hello World!').toString('base64'));
反向(假设您要解码的内容是utf8字符串):
Reverse (assuming the content you're decoding is a utf8 string):
console.log(Buffer.from(b64Encoded, 'base64').toString());
注意:在Node v4之前,请使用new Buffer
而不是Buffer.from
.
Note: prior to Node v4, use new Buffer
rather than Buffer.from
.
这篇关于Node.js抛出“未定义btoa".错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!