37

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?

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.

4 Answers 4

17

With https://github.com/substack/node-browserify you 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

Sign up to request clarification or add additional context in comments.

2 Comments

These days this lives here: github.com/feross/buffer
Now (2022), github.com/StableLib/stablelib/tree/master/packages might bring a solution as well, in particular utf-8 and hex modules
13

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

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

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

1 Comment

11

So I discovered a library I use for web3 included Buffer as a function You can include as CDN:

<script src="https://cdn.jsdelivr.net/gh/ethereumjs/browser-builds/dist/ethereumjs-tx/ethereumjs-tx-1.3.3.min.js"></script>

Then you can use the function as this:

ethereumjs.Buffer.Buffer.from(valueToConvert,'hex');

Comments

-8

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

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

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

3 Comments

No, no, I need an alternative to Buffer(). Thank you anyway :) I need to run it in browsers' javascript.
Note that if the Buffer ends with an incomplete UTF-8 sequence that toString() is not sufficient, you will end up with a broken last character. (This can happen if you are using Buffer to read in a stream with unknown text content.) In this case the solution is to use instead StringDecoder
Bumping +1, this was useful info for me in Node.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.