Node.js Buffer for Browsers (ES6 Rewrite)

4.9.3 · active · verified Tue Apr 21

buffer-es6 provides a robust and performant implementation of the Node.js Buffer API, specifically re-engineered using ES6 syntax for browser environments. It is optimized for bundlers like Rollup, enabling better tree-shaking compared to its predecessor. The current stable version is 4.9.3. While no explicit release cadence is provided, the package appears actively maintained as a specialized fork of the main `buffer` package. Its key differentiators include identical API compatibility with Node.js Buffer, broad browser support (down to IE6), and a remarkably small bundle size (5.04KB minified + gzipped). It internally bundles `ieee754` and `base64-js`, providing a self-contained solution for binary data manipulation in the browser.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates various fundamental Buffer operations including creation, writing, reading, concatenation, and type checking, using ES module syntax.

import { Buffer } from 'buffer-es6';

// Create a new Buffer of 10 bytes and fill it with zeros
const buf1 = Buffer.alloc(10);
console.log('Buffer 1 (alloc):', buf1.toString('hex'));

// Create a Buffer from a string, using UTF-8 encoding
const buf2 = Buffer.from('Hello Buffer!', 'utf8');
console.log('Buffer 2 (from string):', buf2.toString());

// Write data to an existing buffer
buf1.write('ABC', 0, 3, 'utf8');
console.log('Buffer 1 after write:', buf1.toString('utf8'));

// Concatenate two buffers
const buf3 = Buffer.concat([buf1, buf2]);
console.log('Buffer 3 (concat):', buf3.toString('utf8'));

// Check buffer length
console.log('Buffer 3 length:', buf3.length);

// Access individual bytes
console.log('Byte at index 1 of buf2:', buf2[1]); // Prints 'e' ASCII value

// Convert to JSON
const json = buf2.toJSON();
console.log('Buffer 2 as JSON:', json);

// Create a Buffer from a JavaScript ArrayBuffer
const arrayBuffer = new ArrayBuffer(5);
const uint8Array = new Uint8Array(arrayBuffer);
uint8Array[0] = 72; // 'H'
uint8Array[1] = 105; // 'i'
const buf4 = Buffer.from(arrayBuffer);
console.log('Buffer 4 (from ArrayBuffer):', buf4.toString());

// Check if a variable is a Buffer
console.log('Is buf1 a Buffer?', Buffer.isBuffer(buf1));
console.log('Is "Hello" a Buffer?', Buffer.isBuffer('Hello'));

view raw JSON →