This error occurs when Buffer.concat() receives arguments that are not Buffer or Uint8Array instances. The method expects an array containing only Buffer or Uint8Array objects, but receives strings, plain objects, or other incompatible types instead.
Buffer.concat() is a Node.js method that combines multiple Buffer instances into a single Buffer. This error is thrown when the method validates its arguments and discovers that the provided list contains elements that are not Buffer or Uint8Array instances. The error can manifest in several ways depending on the Node.js version. Modern versions may show "ERR_INVALID_ARG_TYPE: The 'list[0]' argument must be one of type Array, Buffer, or Uint8Array. Received type string" while older versions show the simpler "list argument must be an Array of Buffer instances". This typically happens in data processing pipelines where mixed data types accumulate, in stream handling code where chunks are improperly managed, or when working with APIs that return data in unexpected formats.
Add debugging before the Buffer.concat() call to see what types you're actually passing:
// Check what you're trying to concatenate
console.log('Data types:', chunks.map(c => typeof c));
console.log('Is Buffer:', chunks.map(c => Buffer.isBuffer(c)));
console.log('Actual values:', chunks);
const result = Buffer.concat(chunks);This will reveal if strings, objects, or other non-Buffer types have entered your array.
Add validation to ensure all elements are Buffer or Uint8Array instances:
// Filter out invalid elements and convert if possible
const validChunks = chunks
.filter(chunk => chunk != null) // Remove null/undefined
.map(chunk => {
if (Buffer.isBuffer(chunk)) {
return chunk;
}
if (typeof chunk === 'string') {
return Buffer.from(chunk); // Convert strings to Buffer
}
if (chunk instanceof Uint8Array) {
return Buffer.from(chunk); // Convert Uint8Array to Buffer
}
console.warn('Skipping invalid chunk:', typeof chunk);
return null;
})
.filter(chunk => chunk !== null);
const result = Buffer.concat(validChunks);This ensures only valid Buffer instances are concatenated.
Identify where non-Buffer data is being added to your array. Common scenarios:
Stream handling:
// BAD - mixing strings and Buffers
stream.on('data', (chunk) => {
if (someCondition) {
chunks.push(chunk.toString()); // String!
} else {
chunks.push(chunk); // Buffer
}
});
// GOOD - keep everything as Buffer
stream.on('data', (chunk) => {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
});API responses:
// BAD - JSON stringified data
const data = JSON.stringify(obj);
chunks.push(data); // String, not Buffer
// GOOD - convert to Buffer explicitly
const data = JSON.stringify(obj);
chunks.push(Buffer.from(data, 'utf8'));Ensure your chunks array is properly initialized and managed:
let chunks = []; // Start with empty array
// Always validate before adding
function addChunk(data) {
if (data == null) return; // Skip null/undefined
const chunk = Buffer.isBuffer(data)
? data
: Buffer.from(data);
chunks.push(chunk);
}
// Safe concatenation with empty check
function getResult() {
if (chunks.length === 0) {
return Buffer.alloc(0); // Return empty Buffer
}
return Buffer.concat(chunks);
}This prevents accumulating invalid data types throughout your processing pipeline.
Add defensive checks especially when handling external data:
function safeConcatBuffers(bufferList) {
if (!Array.isArray(bufferList)) {
throw new TypeError('Expected an array of Buffers');
}
// Validate all elements
const invalidIndex = bufferList.findIndex(
item => !Buffer.isBuffer(item) && !(item instanceof Uint8Array)
);
if (invalidIndex !== -1) {
throw new TypeError(
`Element at index ${invalidIndex} is not a Buffer or Uint8Array. ` +
`Got: ${typeof bufferList[invalidIndex]}`
);
}
return Buffer.concat(bufferList);
}
// Usage
try {
const result = safeConcatBuffers(chunks);
} catch (err) {
console.error('Buffer concatenation failed:', err.message);
}Buffer and Uint8Array Compatibility:
Node.js Buffer extends Uint8Array, so Buffer instances are valid where Uint8Array is expected. However, not all TypedArray types work with Buffer.concat() - only Uint8Array and its subclasses (including Buffer) are accepted.
Performance Considerations:
If you're concatenating many small Buffers in a loop, consider pre-calculating the total length and passing it as the second argument to Buffer.concat(totalLength). This avoids recalculating the length internally and improves performance.
Stream Best Practices:
When collecting Buffer chunks from streams, always maintain type consistency. If you need to process the data as strings temporarily, convert back to Buffer before concatenation rather than mixing types.
HTTP Buffer Size Limits:
In HTTP servers, exceeding maxHttpBufferSize can cause frameworks to substitute empty strings for Buffers. Configure appropriate limits and handle overflow scenarios explicitly rather than allowing silent type changes.
TypeScript Users:
Use proper typing to catch these errors at compile time:
const chunks: Buffer[] = [];
// TypeScript will catch attempts to add non-Buffer typesError: Listener already called (once event already fired)
EventEmitter listener already called with once()
Error: EACCES: permission denied, open '/root/file.txt'
EACCES: permission denied
Error: Invalid encoding specified (stream encoding not supported)
How to fix Invalid encoding error in Node.js readable streams
Error: EINVAL: invalid argument, open
EINVAL: invalid argument, open
TypeError: readableLength must be a positive integer (stream config)
TypeError: readableLength must be a positive integer in Node.js streams