How can I convert a NodeJS binary buffer into a JavaScript ArrayBuffer?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fs
- Keeping track of variable instances
1. A
Buffer
is just a view for looking into anArrayBuffer
.A
Buffer
, in fact, is aFastBuffer
, whichextends
(inherits from)Uint8Array
, which is an octet-unit view (“partial accessor”) of the actual memory, anArrayBuffer
.You can think of an
ArrayBuffer
as a typedBuffer
.An
ArrayBuffer
therefore always needs a type (the so-called "Array Buffer View"). Typically, the Array Buffer View has a type ofUint8Array
orUint16Array
.There is a good article from Renato Mangini on converting between an ArrayBuffer and a String.
I have summarized the essential parts in a code example (for Node.js). It also shows how to convert between the typed
ArrayBuffer
and the untypedBuffer
.I have already update my node to Version 5.0.0 And I work work with this:
I use it to check my vhd disk image.
Buffers are Uint8Arrays, so you just need to access its ArrayBuffer. This is O(1):
The
slice
and offset stuff is required because small Buffers (<4096 bytes, I think) are views on a shared ArrayBuffer. Without it you might end up with an ArrayBuffer containing data from another TypedArray.Use Martin Thomson's answer, which runs in O(n) time. (See also my replies to comments on his answer about non-optimizations. Using a DataView is slow. Even if you need to flip bytes, there are faster ways to do so.)
You can use https://www.npmjs.com/package/memcpy to go in either direction (Buffer to ArrayBuffer and back). It's faster than the other answers posted here and is a well-written library. Node 0.12 through iojs 3.x require ngossen's fork (see this).
Instances of
Buffer
are also instances ofUint8Array
in node.js 4.x and higher. Thus, the most efficient solution is to access thebuf.buffer
property directly, as per https://stackoverflow.com/a/31394257/1375574. The Buffer constructor also takes an ArrayBufferView argument if you need to go the other direction.Note that this will not create a copy, which means that writes to any ArrayBufferView will write through to the original Buffer instance.
In older versions, node.js has both ArrayBuffer as part of v8, but the Buffer class provides a more flexible API. In order to read or write to an ArrayBuffer, you only need to create a view and copy across.
From Buffer to ArrayBuffer:
From ArrayBuffer to Buffer:
NodeJS, at one point (I think it was v0.6.x) had ArrayBuffer support. I created a small library for base64 encoding and decoding here, but since updating to v0.7, the tests (on NodeJS) fail. I'm thinking of creating something that normalizes this, but till then, I suppose Node's native
Buffer
should be used.