34

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.

Fermuch
  • 457
  • 1
  • 6
  • 11

4 Answers4

15

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

Martin Heidegger
  • 910
  • 7
  • 12
11

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:

The Rover
  • 79
  • 9
michaelhanson
  • 351
  • 2
  • 5
  • 1
    There is now a [browser `Buffer` compatibility library](http://stackoverflow.com/a/12486045/201952). – josh3736 Oct 08 '12 at 23:32
8

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');
eclat_soft
  • 602
  • 7
  • 9
-9

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";
Glenjamin
  • 7,150
  • 6
  • 25
  • 26
  • No, no, I need an alternative to Buffer(). Thank you anyway :) I need to run it in browsers' javascript. – Fermuch Jan 16 '12 at 13:26
  • 1
    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`](http://nodejs.org/api/string_decoder.html) – hippietrail Jan 04 '13 at 22:04
  • Bumping +1, this was useful info for me in Node. – User 1058612 Apr 29 '13 at 14:11