Reputation: 477
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.
Upvotes: 36
Views: 61354
Reputation: 810
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');
Upvotes: 11
Reputation: 369
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:
Upvotes: 13
Reputation: 920
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
Upvotes: 16
Reputation: 7340
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";
Upvotes: -8