Utility functions to make dealing with Uint8Arrays easier
—
Memory allocation functions for creating Uint8Arrays with optimized performance. These functions automatically use Node.js Buffer when available for better performance while maintaining compatibility across all JavaScript environments.
Creates a new Uint8Array with memory initialized to zero values. Safe and predictable for all use cases.
/**
* Returns a Uint8Array of the requested size. Referenced memory will be initialized to 0.
* @param size - Size of the array to allocate (default: 0)
* @returns New Uint8Array with zero-initialized memory
*/
function alloc(size?: number): Uint8Array;Usage Examples:
import { alloc } from "uint8arrays/alloc";
// Create a 10-byte zero-initialized array
const buffer = alloc(10);
console.log(buffer); // Uint8Array(10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
// Create empty array (0 bytes)
const empty = alloc();
console.log(empty.length); // 0
// Useful for preparing buffers for writing
const writeBuffer = alloc(1024);
// All bytes are guaranteed to be 0Creates a new Uint8Array with potentially uninitialized memory for maximum performance. Only use when you will immediately overwrite all values.
/**
* Where possible returns a Uint8Array of the requested size that references
* uninitialized memory. Only use if you are certain you will immediately
* overwrite every value in the returned Uint8Array.
* @param size - Size of the array to allocate (default: 0)
* @returns New Uint8Array with potentially uninitialized memory
*/
function allocUnsafe(size?: number): Uint8Array;Usage Examples:
import { allocUnsafe } from "uint8arrays/alloc";
// Allocate buffer for immediate writing
const buffer = allocUnsafe(8);
// IMPORTANT: Don't read from buffer before writing to it
// Fill with specific pattern
for (let i = 0; i < buffer.length; i++) {
buffer[i] = i * 2;
}
console.log(buffer); // Uint8Array(8) [0, 2, 4, 6, 8, 10, 12, 14]
// Use with APIs that write to buffers
const readBuffer = allocUnsafe(1024);
// Pass to file reading, network operations, etc.Both allocation functions provide platform-specific optimizations:
Buffer.alloc() and Buffer.allocUnsafe() for better performancenew Uint8Array() constructorBoth functions handle edge cases gracefully:
Install with Tessl CLI
npx tessl i tessl/npm-uint8arrays