Buffer Layout

1.2.2 · abandoned · verified Sun Apr 19

buffer-layout is a pure JavaScript utility library designed for translating between JavaScript values and Node.js Buffers. It enables developers to define and manipulate binary data structures that closely mimic C structs, offering explicit control over memory layout and endianness. The library provides layout constructors for various data types, including signed and unsigned integers (1 to 6 bytes, with 64-bit integers decoded as standard JavaScript Numbers), floats, doubles, sequences, complex structures, unions, bit fields, NUL-terminated C strings, and raw data blobs. The current version, 1.2.2, was last published in 2021. Given its age and lack of recent updates on its GitHub repository (last commit approximately four years ago), the project appears to be in an abandoned state, with no active development or maintenance. A key differentiator is its detailed control over C-style memory layouts, including the necessity of manually accounting for padding and bit fields.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates defining both packed and aligned C-style structs using `buffer-layout`, showing how to encode JavaScript objects into Buffers and decode them back, including explicit padding for alignment.

const assert = require('assert');
const lo = require('buffer-layout');

// Define a C-like packed struct without padding
// C: struct { uint8_t a; uint16_t b; } __attribute__((__packed__)) MyPackedStruct;
const packedStruct = lo.struct([
  lo.u8('a'),
  lo.u16le('b') // u16le for unsigned 16-bit little-endian
]);

const packedBuffer = Buffer.alloc(3); // 1 byte for 'a', 2 bytes for 'b'
const data1 = { a: 0x12, b: 0x3456 };
packedStruct.encode(data1, packedBuffer);

console.log('Packed Buffer:', packedBuffer.toString('hex'));
assert.equal(packedBuffer.toString('hex'), '125634');
assert.deepStrictEqual(packedStruct.decode(packedBuffer), data1);

// Define a C-like struct WITH padding, simulating a 32-bit aligned machine
// C: struct { uint8_t v; uint32_t u32; } MyAlignedStruct;
// In C, u32 would typically be 4-byte aligned, causing 3 bytes of padding after u8.
const alignedStruct = lo.struct([
  lo.u8('v'),
  lo.seq(lo.u8(), 3, 'padding'), // explicit padding for 4-byte alignment
  lo.u32le('u32')
]);

const alignedBuffer = Buffer.alloc(8); // 1 byte (v) + 3 bytes (padding) + 4 bytes (u32)
alignedBuffer.fill(0xBD); // Fill with a recognizable pattern for padding
const data2 = { v: 0x01, u32: 0x12345678 };
alignedStruct.encode(data2, alignedBuffer);

console.log('Aligned Buffer (with padding):', alignedBuffer.toString('hex'));
assert.equal(alignedBuffer.toString('hex'), '01bdbdbd78563412');
assert.deepStrictEqual(alignedStruct.decode(alignedBuffer), { v: 1, u32: 0x12345678 });

console.log('Quickstart examples completed successfully.');

view raw JSON →