Core functionality for converting between JavaScript values and CBOR binary format with automatic type detection and comprehensive type support.
Convert JavaScript values to CBOR binary format with automatic type detection.
/**
* Encode JavaScript values to CBOR Buffer
* @param {...any} objs - One or more objects to encode
* @returns {Buffer} CBOR encoded data
*/
function encode(...objs);Usage Examples:
const cbor = require("cbor");
// Encode primitive types
const encodedString = cbor.encode("hello");
const encodedNumber = cbor.encode(42);
const encodedBoolean = cbor.encode(true);
// Encode complex objects
const user = { name: "Alice", age: 30, active: true };
const encodedUser = cbor.encode(user);
// Encode multiple objects at once
const encodedMultiple = cbor.encode("hello", 42, { foo: "bar" });
// Encode arrays
const encodedArray = cbor.encode([1, 2, 3, "four", true]);
// Encode JavaScript types
const encodedComplex = cbor.encode({
date: new Date(),
bigint: 123456789012345678901234567890n,
regex: /pattern/gi,
map: new Map([["key", "value"]]),
set: new Set([1, 2, 3]),
buffer: Buffer.from("data"),
uint8array: new Uint8Array([1, 2, 3, 4])
});Convert CBOR binary data back to JavaScript values.
/**
* Decode CBOR data to JavaScript values (alias for decodeFirstSync)
* @param {BufferLike} input - CBOR data to decode
* @param {DecoderOptions} [options] - Decoding options
* @returns {any} Decoded JavaScript value
*/
function decode(input, options);Usage Examples:
const cbor = require("cbor");
// Basic decoding
const encoded = cbor.encode({ name: "Bob", age: 25 });
const decoded = cbor.decode(encoded);
console.log(decoded); // { name: "Bob", age: 25 }
// Decode with options
const decoded2 = cbor.decode(encoded, {
preferMap: false, // Use plain objects instead of Maps
preferWeb: false // Use Buffers instead of Uint8Arrays
});
// Decode from different input types
const hexString = "a2646e616d65634426b62636167652018";
const decodedFromHex = cbor.decode(hexString, { encoding: 'hex' });
const base64String = "omRuYW1lY0JvYmNhZ2UY";
const decodedFromBase64 = cbor.decode(base64String, { encoding: 'base64' });Encode objects using CBOR's canonical encoding rules for consistent, reproducible output.
/**
* Encode objects canonically to CBOR Buffer
* @param {...any} objs - Objects to encode canonically
* @returns {Buffer} Canonical CBOR encoded data
*/
function encodeCanonical(...objs);Usage Examples:
const cbor = require("cbor");
// Canonical encoding ensures consistent key ordering and formatting
const obj = { z: 1, a: 2, m: 3 };
const canonical = cbor.encodeCanonical(obj);
// Multiple objects
const canonicalMultiple = cbor.encodeCanonical(
{ name: "Alice" },
{ name: "Bob" },
[1, 2, 3]
);Encode a single object with detailed configuration options.
/**
* Encode single object with options
* @param {any} obj - Object to encode
* @param {EncodingOptions} [options] - Encoding options
* @returns {Buffer} CBOR encoded data
*/
function encodeOne(obj, options);Usage Examples:
const cbor = require("cbor");
// Basic encoding with options
const encoded = cbor.encodeOne({ name: "Charlie", age: 35 }, {
canonical: true,
dateType: 'string',
omitUndefinedProperties: true
});
// Custom semantic types
const encodedWithCustomTypes = cbor.encodeOne(myObject, {
genTypes: [
// Add custom encoder for a specific class
[MyClass, (encoder, obj) => {
encoder.pushAny(obj.serialize());
return true;
}]
]
});
// Loop detection
const circularObj = { name: "test" };
circularObj.self = circularObj;
const encodedSafe = cbor.encodeOne(circularObj, {
detectLoops: true // Prevents infinite recursion
});
// Date encoding options
const dateObj = { timestamp: new Date() };
const encodedDates = cbor.encodeOne(dateObj, {
dateType: 'string' // 'number', 'float', 'int', or 'string'
});Encode large objects asynchronously to avoid blocking the event loop.
/**
* Async encode for large objects
* @param {any} obj - Object to encode
* @param {EncodingOptions} [options] - Encoding options
* @returns {Promise<Buffer>} Promise resolving to CBOR encoded data
*/
function encodeAsync(obj, options);Usage Examples:
const cbor = require("cbor");
// Async encoding for large datasets
async function encodeLargeData() {
const largeArray = new Array(1000000).fill(0).map((_, i) => ({
id: i,
data: `item-${i}`,
timestamp: new Date()
}));
const encoded = await cbor.encodeAsync(largeArray, {
canonical: true,
dateType: 'number'
});
return encoded;
}
// With error handling
async function safeEncodeAsync(data) {
try {
const result = await cbor.encodeAsync(data, {
detectLoops: true,
omitUndefinedProperties: true
});
return result;
} catch (error) {
console.error('Encoding failed:', error);
throw error;
}
}CBOR encoding automatically handles these JavaScript types:
string, number, boolean, null, undefinedDate, RegExp, Buffer, ArrayBuffer, TypedArraysMap, SetBigInt (encoded as CBOR bignums)NaN, Infinity, -InfinityEncoding functions can throw errors for:
detectLoops is disabled)const cbor = require("cbor");
try {
const encoded = cbor.encode(problematicData);
} catch (error) {
if (error.message.includes('circular')) {
console.log('Circular reference detected');
}
// Handle other encoding errors
}