将 nodejs 的 Buffer 转换为浏览器的 javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8880571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:51:37  来源:igfitidea点击:

Convert nodejs' Buffer to browsers' javascript

javascriptnode.jsbuffer

提问by Fermuch

I'm converting my code from Node.js to browsers' javascript, but I have a problem with the Buffers in node.js. How can I use them in Javascript?

我正在将我的代码从 Node.js 转换为浏览器的 javascript,但是我在 node.js 中遇到了缓冲区问题。我如何在 Javascript 中使用它们?

Here's an example:

下面是一个例子:

new Buffer("foo", encoding='utf8')
<Buffer 66 6f 6f>

I need to transform [66, 6f, 6f] in javascript to "foo" and vice-versa. How can I do that? NOTE: this must be done without Node.js.

我需要将 javascript 中的 [66, 6f, 6f] 转换为“foo”,反之亦然。我怎样才能做到这一点?注意:这必须在没有 Node.js 的情况下完成。

采纳答案by Martin Heidegger

With https://github.com/substack/node-browserifyyou can work with buffers in the Browser by using: https://github.com/toots/buffer-browserify. However: this can be very slow in the browser: For faster access use https://github.com/chrisdickinson/bops

使用https://github.com/substack/node-browserify,您可以使用浏览器中的缓冲区:https: //github.com/toots/buffer-browserify。但是:这在浏览器中可能会很慢:为了更快地访问,请使用https://github.com/chrisdickinson/bops

回答by michaelhanson

There is no direct support for Buffer in browser-based JavaScript, and I am not aware of any compatibility library that implements the Buffer API (yet).

在基于浏览器的 JavaScript 中没有对 Buffer 的直接支持,而且我不知道有任何实现 Buffer API 的兼容库(目前)。

The equivalent functionality in the browser is provided by TypedArrays. You can learn about them here:

浏览器中的等效功能由 TypedArrays 提供。您可以在此处了解它们:

When porting a Node Buffer-based implementation to browser-based JavaScript, I found these answers helpful:

将基于 Node Buffer 的实现移植到基于浏览器的 JavaScript 时,我发现这些答案很有帮助:

回答by Glenjamin

To convert back to the string, use the buffer's toString method with a supplied encoding.

要转换回字符串,请使用缓冲区的 toString 方法和提供的编码。

http://nodejs.org/docs/latest/api/buffers.html#buffer.toString

http://nodejs.org/docs/latest/api/buffers.html#buffer.toString

var buffer = new Buffer("foo", "utf8");
var str = buffer.toString("utf8");
str === "foo";