This error occurs when attempting to create a Buffer with a malformed hexadecimal string. The hex string must contain an even number of valid hexadecimal characters, with each pair representing a single byte.
Node.js throws this TypeError when you try to convert a hexadecimal string to a Buffer using Buffer.from() or the deprecated new Buffer() constructor with invalid hex data. The error specifically indicates that the provided string either has an odd number of characters (each hex byte requires exactly 2 characters) or contains non-hexadecimal characters. Hexadecimal strings must consist exclusively of valid hex digits (0-9, a-f, A-F) with an even count for proper byte pairing.
Check that your hex string has an even number of characters. Each hexadecimal digit pair represents one byte.
const hexString = "1a2b"; // Valid - 4 characters (2 bytes)
const invalid = "1a2"; // Invalid - 3 characters (odd)
if (hexString.length % 2 !== 0) {
console.error("Hex string has odd length:", hexString.length);
}If your string has odd length, you may need to pad it:
const hexString = "1a2";
const padded = hexString.padStart(hexString.length + 1, "0"); // "01a2"
const buffer = Buffer.from(padded, "hex");Ensure the string contains only valid hexadecimal characters (0-9, a-f, A-F). Invalid characters will cause the error or produce unexpected results.
const hexRegex = /^[0-9a-fA-F]*$/;
const hexString = "1a2bZZ"; // Contains invalid characters Z, Z
if (!hexRegex.test(hexString)) {
console.error("Hex string contains invalid characters");
}
const validHex = "1a2b3c"; // Valid
const buffer = Buffer.from(validHex, "hex");Remove whitespace and normalize the hex string before conversion:
const rawInput = " 1a 2b 3c "; // From external source
const normalized = rawInput.trim().replace(/\s+/g, "").toLowerCase();
if (normalized.length % 2 !== 0) {
throw new Error("Invalid hex string length");
}
const buffer = Buffer.from(normalized, "hex");
console.log(buffer); // <Buffer 1a 2b 3c>Create a helper function to safely convert hex strings to buffers:
function safeHexToBuffer(hexString) {
const cleaned = hexString.trim().replace(/\s+/g, "").toLowerCase();
// Validate length
if (cleaned.length % 2 !== 0) {
throw new Error("Hex string must have even length");
}
// Validate characters
if (!/^[0-9a-f]*$/.test(cleaned)) {
throw new Error("Hex string contains invalid characters");
}
return Buffer.from(cleaned, "hex");
}
// Usage
try {
const buffer = safeHexToBuffer("1a2b3c");
console.log("Success:", buffer);
} catch (err) {
console.error("Invalid hex:", err.message);
}If receiving hex strings from external sources (APIs, files), debug the raw input:
const fromAPI = '"1a2b3c"'; // With quotes
const rawData = fromAPI.slice(1, -1); // Remove quotes
console.log("Raw data length:", rawData.length);
console.log("Raw data:", JSON.stringify(rawData));
console.log("Character codes:", [...rawData].map(c => c.charCodeAt(0)));
const buffer = Buffer.from(rawData, "hex");Common issues:
- JSON-parsed strings still contain escaped characters
- API responses wrapped in quotes or brackets
- Unicode normalization changing character count
- Hidden whitespace or BOM markers
Node.js versions have inconsistent behavior with invalid hex strings. Older versions (pre-7.0) would silently ignore invalid characters and return partial buffers, while newer versions may throw TypeErrors. The safest approach is to validate input before conversion rather than relying on error handling. If processing large amounts of hex data, consider using regex-based validation or a hex validation library. For cryptographic operations with hex keys, always implement strict validation to prevent security issues from silently corrupted keys.
Error: 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