2.6 KiB
2.6 KiB
bufferToUint8Array
(no submodules)
Purpose
bufferToUint8Array normalises the two byte-container shapes that show up in
mixed Node/browser code — Buffer and ArrayBuffer — into the single
canonical Uint8Array form used throughout @suaveplan/streams. The streams
package treats Uint8Array as the universal byte chunk; this helper lets call
sites accept either input without sprinkling instanceof checks across every
adapter.
The conversion is zero-copy. For Buffer inputs we construct a view that
respects the source's byteOffset / byteLength, which matters because Node
typically slices new Buffers out of a shared pool. For ArrayBuffer inputs
we wrap the entire buffer.
Features
- Accepts both Node
Bufferand standardArrayBufferinputs. - Zero-copy: never allocates a new backing buffer.
- Honours
Buffer.subarrayoffsets correctly (avoids a common foot-gun). - Pure synchronous function with no dependencies.
Usage: Basic Example
import { bufferToUint8Array } from "@suaveplan/streams/utils/buffer/buffer-to-uint8/buffer-to-uint8";
const u8 = bufferToUint8Array(Buffer.from("hello"));
console.log(u8.byteLength); // 5
Usage: Advanced Example
import { bufferToUint8Array } from "@suaveplan/streams/utils/buffer/buffer-to-uint8/buffer-to-uint8";
// Coming from `node:fs/promises#readFile` (returns Buffer in Node)
async function loadAsU8(path: string): Promise<Uint8Array> {
const { readFile } = await import("node:fs/promises");
return bufferToUint8Array(await readFile(path));
}
// Coming from a browser `Response.arrayBuffer()`
async function fetchAsU8(url: string): Promise<Uint8Array> {
const ab = await (await fetch(url)).arrayBuffer();
return bufferToUint8Array(ab);
}
API Reference
bufferToUint8Array(buffer: Buffer | ArrayBuffer): Uint8Array
buffer— either a NodeBuffer(aUint8Arraysubclass with possibly non-zerobyteOffset) or a standard DOM/ESArrayBuffer.- Returns — a
Uint8Arrayview over the same memory as the input. - Throws — never; type narrowing is performed via
instanceof ArrayBuffer.
Implementation Notes
- The
instanceof ArrayBuffercheck intentionally precedes theBufferbranch becauseBuffer instanceof ArrayBufferisfalsein Node (Buffer extendsUint8Array, notArrayBuffer). - The returned view shares memory with the source. If you need an independent
copy, follow up with
.slice()or pair this helper withcreateUint8ArraySlice. - Universal: this module has no Node-only or DOM-only imports.