Buffer size is not a multiple of the word size
Production Risk
Low — caught immediately at call site; affects binary protocol or image processing code.
Thrown when a Buffer method that operates on multi-byte values (such as buf.swap16(), buf.swap32(), buf.swap64()) is called on a buffer whose byte length is not an exact multiple of the element size (2, 4, or 8 bytes respectively). Swapping requires complete elements.
- 1Calling buf.swap16() on a buffer with an odd byte length
- 2Calling buf.swap32() on a buffer whose length is not divisible by 4
- 3Calling buf.swap64() on a buffer whose length is not divisible by 8
Triggered when swap16/32/64 is called on a buffer that cannot be evenly divided into the target element size.
const buf = Buffer.from([0x01, 0x02, 0x03]); // 3 bytes buf.swap16(); // throws — 3 is not a multiple of 2
expected output
RangeError [ERR_INVALID_BUFFER_SIZE]: Buffer size must be a multiple of 16-bits
Fix 1
Ensure the buffer length is a multiple of the swap unit
WHEN Before calling any swap method
const buf = Buffer.from([0x01, 0x02, 0x03, 0x04]); // 4 bytes buf.swap16(); // ok — 4 is a multiple of 2 buf.swap32(); // ok — 4 is a multiple of 4
Why this works
Swap methods require complete element pairs; ensuring the length is aligned satisfies the check.
Fix 2
Validate buffer length before swapping
WHEN When buffer size comes from external data
if (buf.length % 2 !== 0) throw new Error('Buffer must be 16-bit aligned');
buf.swap16();Why this works
A guard prevents the swap from being called on a misaligned buffer.
const buf = Buffer.from([0x01, 0x02, 0x03]); // 3 bytes buf.swap16(); // throws — 3 is not a multiple of 2 // this triggers ERR_INVALID_BUFFER_SIZE
try {
// operation that may throw ERR_INVALID_BUFFER_SIZE
riskyOperation()
} catch (err) {
if (err.code === 'ERR_INVALID_BUFFER_SIZE') {
console.error('ERR_INVALID_BUFFER_SIZE:', err.message)
} else {
throw err
}
}// Validate inputs before calling the operation
function safe_err_invalid_buffer_size(...args) {
// validate args here
return performOperation(...args)
}✕ Call swap16/32/64 without verifying alignment
Unaligned buffers cannot be swapped in place; the operation is undefined for partial elements.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev