You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.9 KiB

4 years ago
  1. # Buffer From
  2. A [ponyfill](https://ponyfill.com) for `Buffer.from`, uses native implementation if available.
  3. ## Installation
  4. ```sh
  5. npm install --save buffer-from
  6. ```
  7. ## Usage
  8. ```js
  9. const bufferFrom = require('buffer-from')
  10. console.log(bufferFrom([1, 2, 3, 4]))
  11. //=> <Buffer 01 02 03 04>
  12. const arr = new Uint8Array([1, 2, 3, 4])
  13. console.log(bufferFrom(arr.buffer, 1, 2))
  14. //=> <Buffer 02 03>
  15. console.log(bufferFrom('test', 'utf8'))
  16. //=> <Buffer 74 65 73 74>
  17. const buf = bufferFrom('test')
  18. console.log(bufferFrom(buf))
  19. //=> <Buffer 74 65 73 74>
  20. ```
  21. ## API
  22. ### bufferFrom(array)
  23. - `array` &lt;Array&gt;
  24. Allocates a new `Buffer` using an `array` of octets.
  25. ### bufferFrom(arrayBuffer[, byteOffset[, length]])
  26. - `arrayBuffer` &lt;ArrayBuffer&gt; The `.buffer` property of a TypedArray or ArrayBuffer
  27. - `byteOffset` &lt;Integer&gt; Where to start copying from `arrayBuffer`. **Default:** `0`
  28. - `length` &lt;Integer&gt; How many bytes to copy from `arrayBuffer`. **Default:** `arrayBuffer.length - byteOffset`
  29. When passed a reference to the `.buffer` property of a TypedArray instance, the
  30. newly created `Buffer` will share the same allocated memory as the TypedArray.
  31. The optional `byteOffset` and `length` arguments specify a memory range within
  32. the `arrayBuffer` that will be shared by the `Buffer`.
  33. ### bufferFrom(buffer)
  34. - `buffer` &lt;Buffer&gt; An existing `Buffer` to copy data from
  35. Copies the passed `buffer` data onto a new `Buffer` instance.
  36. ### bufferFrom(string[, encoding])
  37. - `string` &lt;String&gt; A string to encode.
  38. - `encoding` &lt;String&gt; The encoding of `string`. **Default:** `'utf8'`
  39. Creates a new `Buffer` containing the given JavaScript string `string`. If
  40. provided, the `encoding` parameter identifies the character encoding of
  41. `string`.
  42. ## See also
  43. - [buffer-alloc](https://github.com/LinusU/buffer-alloc) A ponyfill for `Buffer.alloc`
  44. - [buffer-alloc-unsafe](https://github.com/LinusU/buffer-alloc-unsafe) A ponyfill for `Buffer.allocUnsafe`