JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 19174527
  • Score
    100M100P100Q240329F
  • License MIT

Convert a typed array to a Buffer without a copy

Package Exports

  • typedarray-to-buffer

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (typedarray-to-buffer) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

typedarray-to-buffer travis npm gittip

Convert a typed array to a Buffer without a copy.

testling badge

Say you're using the 'buffer' module on npm, or browserify and you're working with lots of binary data.

Unfortunately, sometimes the browser or someone else's API gives you an ArrayBuffer or typed array (Uint8Array, etc.) to work with and you need to convert it to a Buffer. What do you do?

Of course: new Buffer(uint8array)

But, alas, every time you do new Buffer(uint8array), the entire array gets copied into a new typed array. This is expensive. The Buffer constructor does a copy; this is defined by the node docs, so it can't be easily changed and the 'buffer' module matches the node API exactly.

So, what can you do if you're writing a performance critical application and can't afford extra copies for no good reason?

Use this module, of course!

install

npm install typedarray-to-buffer

usage

To convert a typed array to a Buffer without a copy, do this:

var toBuffer = require('typedarray-to-buffer')

var arr = new Uint8Array([1, 2, 3])
arr = toBuffer(arr)

// arr is a buffer now!

arr.toString()  // '\u0001\u0002\u0003'
arr.readUInt16BE(0)  // 258

some advanced details

In the case that the browser actually supports typed arrays, you don't even need to use the return value of toBuffer since the original Uint8Array has been augmented with all the methods from Buffer. See how does Buffer work? for why we do this.

If the browser doesn't support typed arrays then the only way we can give a buffer is to return it you. So, just always use the return value if you want to support all browsers!

license

MIT. Copyright (C) Feross Aboukhadijeh.