Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert nodejs' Buffer to browsers' javascript

Tags:

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.

like image 495
Fermuch Avatar asked Jan 16 '12 13:01

Fermuch


2 Answers

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

like image 171
Martin Heidegger Avatar answered Sep 19 '22 13:09

Martin Heidegger


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:

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays

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

  • Converting between strings and ArrayBuffers
  • Javascript - Converting between Unicode string and ArrayBuffer
like image 37
michaelhanson Avatar answered Sep 17 '22 13:09

michaelhanson