“btoa未定义”错误

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.

在我的node.js应用程序我做了一个npm安装btoa-atob,这样我就可以使用btoa()和atob()函数,这些函数在客户端javascript中是原生的,但由于某些原因没有包含在节点中。新的目录出现在我的node_modules文件夹中,它本身与app.js一起在根目录中。然后,我确保在包中添加btu -atob作为依赖项。根目录中的json文件。

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

^应该输出“SGVsbG8gV29ybGQh”到控制台,而是我得到错误“btoa不是defiend。”

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

我没有正确地安装吗?我忽略了什么呢?

5 个解决方案

#1


219  

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

“btu -atob”模块不导出编程接口,它只提供命令行实用程序。

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

如果需要转换到Base64,可以使用Buffer:

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

  

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

反向(假设您正在解码的内容是utf8字符串):

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

  


Note: prior to Node v4, use new Buffer rather than Buffer.from.

注意:在节点v4之前,使用新的缓冲区而不是缓冲区。

#2


12  

My team ran into this problem when using Node with React Native and PouchDB. Here is how we solved it...

我的团队在使用带有React Native和PouchDB的Node时遇到了这个问题。这是我们解决它的方法……

NPM install buffer:

NPM安装缓冲:

$ npm install --save buffer

  

Ensure Bufferbtoa, and atob are loaded as a globals:

确保缓冲区、btoa和atob作为全局加载:

global.Buffer = global.Buffer || require('buffer').Buffer;

if (typeof btoa === 'undefined') {
  global.btoa = function (str) {
    return new Buffer(str, 'binary').toString('base64');
  };
}

if (typeof atob === 'undefined') {
  global.atob = function (b64Encoded) {
    return new Buffer(b64Encoded, 'base64').toString('binary');
  };
}

  

#3


4  

The solutions posted here don't work in non-ascii characters 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'.

如果您打算在节点之间交换base64,那么这里发布的解决方案在非ascii字符中不起作用。js和浏览器。为了使它工作,你必须把输入文本标记为“二进制”。

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:

这给了你SOlsbPMgd / NybGQhIQ = =。如果您在浏览器中创建atob('SOlsbPMgd/NybGQhIQ= '),它将以正确的方式对其进行解码。它也会在结点上做。js通过:

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:

我是从btoa npm包的实现中得到的:

#4


3  

I found that although the shims from answers above worked, they did not match the behaviour of desktop browsers' implementations of btoa() and atob():

我发现虽然上面回答的shims起作用,但是它们与桌面浏览器的btoa()和atob()实现的行为不匹配:

const btoa = function(str){ return Buffer.from(str).toString('base64'); }
// returns "4pyT", yet in desktop Chrome would throw an error.
btoa('✓');
// returns "fsO1w6bCvA==", yet in desktop Chrome would return "fvXmvA=="
btoa(String.fromCharCode.apply(null, new Uint8Array([0x7e, 0xf5, 0xe6, 0xbc])));

  

As it turns out, Buffer instances represent/interpret strings encoded in UTF-8 by default. By contrast, in desktop Chrome, you can't even input a string that contains characters outside of the latin1 range into btoa(), as it will throw an exception: Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

事实证明,缓冲区实例表示/解释默认编码为UTF-8的字符串。相比之下,在桌面Chrome中,您甚至不能将包含latin1范围之外字符的字符串输入到btoa()中,因为它将抛出一个异常:Uncaught DOMException:未能在“窗口”上执行“btoa”:要编码的字符串包含latin1范围之外的字符。

Therefore, you need to explicitly set the encoding type to latin1 in order for your Node.js shim to match the encoding type of desktop Chrome:

因此,需要为节点显式地将编码类型设置为latin1。js shim匹配桌面Chrome编码类型:

const btoaLatin1 = function(str) { return Buffer.from(str, 'latin1').toString('base64'); }
const atobLatin1 = function(b64Encoded) {return Buffer.from(b64Encoded, 'base64').toString('latin1');}

const btoaUTF8 = function(str) { return Buffer.from(str, 'utf8').toString('base64'); }
const atobUTF8 = function(b64Encoded) {return Buffer.from(b64Encoded, 'base64').toString('utf8');}

btoaLatin1('✓'); // returns "Ew==" (would be preferable for it to throw error because this is undecodable)
atobLatin1(btoa('✓')); // returns "\u0019" (END OF MEDIUM)

btoaUTF8('✓'); // returns "4pyT"
atobUTF8(btoa('✓')); // returns "✓"

// returns "fvXmvA==", just like desktop Chrome
btoaLatin1(String.fromCharCode.apply(null, new Uint8Array([0x7e, 0xf5, 0xe6, 0xbc])));
// returns "fsO1w6bCvA=="
btoaUTF8(String.fromCharCode.apply(null, new Uint8Array([0x7e, 0xf5, 0xe6, 0xbc])));

  

#5


0  

I understand this is a discussion point for a node application, but in the interest of universal JavaScript applications running on a node server, which is how I arrived at this post, I have been researching this for a universal / isomorphic react app I have been building, and the package abab worked for me. In fact it was the only solution I could find that worked, rather than using the Buffer method also mentioned (I had typescript issues).

我理解这是一个讨论点对于一个节点的应用程序,但在普遍的兴趣节点服务器上运行的JavaScript应用程序,这是我来到这篇文章中,我一直在研究这一普遍/同构应用反应我一直建筑,和包abab为我工作。事实上,这是我能找到的唯一可行的解决方案,而不是使用同样提到的缓冲区方法(我有打字稿问题)。

(This package is used by jsdom, which in turn is used by the window package.)

(这个包由jsdom使用,反过来窗口包也使用这个包。)

Getting back to my point; based on this, perhaps if this functionality is already written as an npm package like the one you mentioned, and has it's own algorithm based on W3 spec, you could install and use the abab package rather than writing you own function that may or may not be accurate based on encoding.

回到我的观点;在此基础上,如果这个功能已经写成一个npm包就像你提到的,和它的算法基于W3规范,你可以安装和使用abab包而不是写你自己的函数,它可能是也可能不是精确的基于编码。

---EDIT---

- - -编辑- - - - - -

I started having weird issues today with encoding (not sure why it's started happening now) with package abab. It seems to encode correctly most of the time, but sometimes on front end it encodes incorrectly. Spent a long time trying to debug, but switched to package base-64 as recommended, and it worked straight away. Definitely seemed to be down to the base64 algorithm of abab.

我今天开始有一些奇怪的问题,编码(不确定为什么它现在开始发生)和包abab。它似乎在大多数时候都是正确编码的,但有时在前端的编码是错误的。花了很长时间尝试调试,但是按照推荐的方式切换到package base-64,并且立即开始工作。看来肯定是abab的base64算法。

 

 

原文地址:http://www.itdaan.com/blog/2014/04/16/a5f1b4d77e59c12de145c4c2997e4ec3.html

posted @ 2019-05-13 17:20  半前端半设计的四不像  阅读(1919)  评论(0编辑  收藏  举报