CBOR is a comprehensive JavaScript library for encoding and parsing data in the Concise Binary Object Representation (CBOR) data format as defined in RFC8949. It provides both synchronous and asynchronous encoding/decoding capabilities, supports streaming operations for large data sets, and offers extensive type support including JavaScript primitives, complex objects, TypedArrays, BigInt, Date, RegExp, URL, Map, and Set.
npm install cborconst cbor = require("cbor");
const { encode, decode, Encoder, Decoder } = require("cbor");ES modules:
import cbor from "cbor";
import { encode, decode, Encoder, Decoder } from "cbor";const cbor = require("cbor");
// Simple encoding and decoding
const data = { name: "Alice", age: 30, tags: ["user", "admin"] };
const encoded = cbor.encode(data);
const decoded = cbor.decode(encoded);
// Working with complex types
const complexData = {
timestamp: new Date(),
bigNumber: 123456789012345678901234567890n,
regex: /pattern/gi,
map: new Map([["key1", "value1"], ["key2", "value2"]]),
set: new Set([1, 2, 3]),
buffer: Buffer.from("hello"),
};
const encodedComplex = cbor.encode(complexData);
const decodedComplex = cbor.decode(encodedComplex);
// Async operations for large data
async function processLargeData() {
const largeData = generateLargeDataSet();
const encoded = await cbor.encodeAsync(largeData);
const decoded = await cbor.decodeFirst(encoded);
return decoded;
}CBOR is built around several key components:
encode, decode) for simple encoding/decoding operationsEncoder and Decoder classes for stream-based processing of large dataTagged class for handling CBOR semantic tags and custom type extensionsSimple, Map classes for CBOR-specific data representationsEssential functions for converting between JavaScript values and CBOR binary format. Supports all JavaScript types with automatic type detection and conversion.
/**
* Encode JavaScript values to CBOR Buffer
* @param {...any} objs - Objects to encode
* @returns {Buffer} CBOR encoded data
*/
function encode(...objs);
/**
* 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);
/**
* Encode objects canonically to CBOR Buffer
* @param {...any} objs - Objects to encode canonically
* @returns {Buffer} Canonical CBOR encoded data
*/
function encodeCanonical(...objs);
/**
* 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);
/**
* 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);Stream-based encoding and decoding for handling large datasets and real-time data processing with memory efficiency.
/**
* Stream-based encoder for CBOR data
*/
class Encoder extends Transform {
constructor(options);
/**
* Add custom semantic type encoder
* @param {string|Function} type - Type name or constructor
* @param {EncodeFunction} func - Encoding function
*/
addSemanticType(type, func);
/**
* Encode any supported type
* @param {any} obj - Object to encode
* @returns {boolean} Success indicator
*/
pushAny(obj);
}
/**
* Stream-based decoder for CBOR data
*/
class Decoder extends Transform {
constructor(options);
/**
* Stop processing
*/
close();
}
/**
* Stream-based encoder with value sharing support
*/
class SharedValueEncoder extends Encoder {
constructor(options);
/**
* Stop recording object references and begin emitting sharing tags
*/
stopRecording();
/**
* Clear recorded objects and restart tracking
*/
clearRecording();
}Comprehensive decoding functions with support for multiple items, async operations, and extended result information.
/**
* Decode all CBOR items from input
* @param {BufferLike} input - CBOR data
* @param {DecoderOptions|decodeCallback} [options] - Options or callback
* @param {decodeCallback} [cb] - Callback function
* @returns {Promise<any[]>|void} Decoded items or void if callback provided
*/
function decodeAll(input, options, cb);
/**
* Decode first CBOR item from input (async)
* @param {BufferLike} input - CBOR data
* @param {DecoderOptions|decodeCallback} [options] - Options or callback
* @param {decodeCallback} [cb] - Callback function
* @returns {Promise<any>|void} Decoded item or void if callback provided
*/
function decodeFirst(input, options, cb);
/**
* Synchronously decode all CBOR items
* @param {BufferLike} input - CBOR data
* @param {DecoderOptions} [options] - Decoding options
* @returns {any[]} Array of decoded items
*/
function decodeAllSync(input, options);
/**
* Synchronously decode first CBOR item
* @param {BufferLike} input - CBOR data
* @param {DecoderOptions} [options] - Decoding options
* @returns {any} Decoded item
*/
function decodeFirstSync(input, options);Special CBOR types for representing semantic values, tagged data, and CBOR-specific data structures.
/**
* Represent CBOR Simple Values
*/
class Simple {
constructor(value);
/**
* Test if object is a Simple value
* @param {any} obj - Object to test
* @returns {boolean} True if Simple value
*/
static isSimple(obj);
}
/**
* Represent CBOR tagged items with semantic meaning
*/
class Tagged {
constructor(tag, value, err);
/**
* Convert using provided converters
* @param {Object} converters - Tag conversion functions
* @returns {any} Converted value
*/
convert(converters);
}
/**
* CBOR Map with complex key support and value-based comparison
*/
class Map extends Map {
constructor(iterable);
/**
* Set key-value pair (keys compared by value)
* @param {any} key - Map key
* @param {any} val - Map value
* @returns {Map} This map instance
*/
set(key, val);
}Tools for generating human-readable diagnostic output and commented CBOR format for debugging and analysis.
/**
* Generate diagnostic format string from CBOR data
* @param {BufferLike} input - CBOR data
* @param {DiagnoseOptions|diagnoseCallback} [options] - Options or callback
* @param {diagnoseCallback} [cb] - Callback function
* @returns {Promise<string>|void} Diagnostic string or void if callback provided
*/
function diagnose(input, options, cb);
/**
* Generate commented CBOR format for debugging
* @param {BufferLike} input - CBOR data
* @param {CommentOptions|commentCallback} [options] - Options or callback
* @param {commentCallback} [cb] - Callback function
* @returns {Promise<string>|void} Commented format or void if callback provided
*/
function comment(input, options, cb);Integration support for databases and frameworks, plus utility functions for package management.
/**
* Codec for leveldb integration
*/
const leveldb = {
decode: Function,
encode: Function,
buffer: true,
name: "cbor"
};
/**
* Reset encoder/decoder semantic types to defaults
*/
function reset();Error classes and error handling patterns for CBOR operations.
/**
* Error for unexpected CBOR data during decoding
*/
class UnexpectedDataError extends Error {
constructor(byte, value);
/**
* Error name identifier
* @type {string}
*/
name;
/**
* The unexpected byte value
* @type {number}
*/
byte;
/**
* The context value where the error occurred
* @type {any}
*/
value;
}Usage Examples:
const cbor = require("cbor");
try {
// Attempt to decode invalid CBOR data
const result = cbor.decode(Buffer.from([0xFF, 0xFF]));
} catch (error) {
if (error instanceof cbor.UnexpectedDataError) {
console.log('Unexpected byte:', error.byte.toString(16));
console.log('Context value:', error.value);
} else {
console.log('Other error:', error.message);
}
}
// Stream error handling
const decoder = new cbor.Decoder();
decoder.on('error', (error) => {
if (error instanceof cbor.UnexpectedDataError) {
console.log('Stream decode error at byte:', error.byte);
}
});/**
* Types that can act as inputs for decoding
* @typedef {string|Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray|DataView|stream.Readable} BufferLike
*/
/**
* Decoder configuration options
* @typedef {Object} DecoderOptions
* @property {number} [max_depth=-1] - Maximum depth to parse
* @property {TagMap} [tags] - Tag number to function mappings
* @property {boolean} [preferMap=false] - Prefer Map instances over plain objects
* @property {boolean} [preferWeb=false] - Prefer Uint8Arrays over Buffers
* @property {BufferEncoding} [encoding='hex'] - Input encoding if input is string
* @property {boolean} [required=false] - Error on no data
* @property {boolean} [extendedResults=false] - Emit extended result objects
* @property {boolean} [preventDuplicateKeys=false] - Error on duplicate map keys
*/
/**
* Extended result object with additional metadata
* @typedef {Object} ExtendedResults
* @property {any} value - The decoded value
* @property {number} length - Bytes read from original input
* @property {Buffer} bytes - Bytes used to produce the value
* @property {Buffer} [unused] - Leftover bytes from input
*/
/**
* Encoder configuration options
* @typedef {Object} EncodingOptions
* @property {Array|Object} [genTypes] - Custom semantic types
* @property {boolean} [canonical=false] - Use canonical encoding
* @property {boolean|WeakSet} [detectLoops=false] - Loop detection
* @property {string} [dateType='number'] - Date encoding type
* @property {boolean} [collapseBigIntegers=false] - Encode BigInts as integers when possible
* @property {boolean} [omitUndefinedProperties=false] - Skip undefined object properties
* @property {any} [encodeUndefined] - How to encode undefined values
* @property {boolean} [disallowUndefinedKeys=false] - Disallow undefined as map key
* @property {number} [chunkSize] - Chunk size for indefinite encoding
*/
/**
* Decode callback function
* @callback decodeCallback
* @param {Error} [error] - Error if one occurred
* @param {any} [value] - Decoded value
*/
/**
* Semantic type encoder function
* @callback EncodeFunction
* @param {Encoder} enc - Encoder instance
* @param {any} val - Value to encode
* @returns {boolean} Success indicator
*/
/**
* Tag conversion function
* @callback TagFunction
* @param {any} val - Tagged value
* @returns {any} Converted value
*/
/**
* Mapping of tag numbers to conversion functions
* @typedef {Object.<number, TagFunction>} TagMap
*/
/**
* Mapping of type names to encoder functions
* @typedef {Object.<string, EncodeFunction>} SemanticMap
*/
/**
* Comment generation callback function
* @callback commentCallback
* @param {Error} [error] - Error if one occurred
* @param {string} [commented] - The comment string
*/
/**
* Diagnose callback function
* @callback diagnoseCallback
* @param {Error} [error] - Error if one occurred
* @param {string} [result] - Diagnostic format string
*/
/**
* Comment generation options
* @typedef {Object} CommentOptions
* @property {number} [max_depth=10] - How many times to indent the dashes
* @property {number} [depth=1] - Initial indentation depth
* @property {boolean} [no_summary=false] - If true, omit summary of bytes read
* @property {TagMap} [tags] - Tag number to function mappings
* @property {boolean} [preferWeb=false] - Prefer Uint8Arrays over Buffers
* @property {BufferEncoding} [encoding='hex'] - Input encoding if input is string
*/
/**
* Diagnostic generation options
* @typedef {Object} DiagnoseOptions
* @property {number} [float_bytes] - Float byte precision for display
* @property {string} [separator] - Object separator character
* @property {boolean} [stream_errors] - Include errors in stream output
* @property {number} [max_depth] - Maximum depth to process
* @property {BufferEncoding} [encoding] - Input encoding if input is string
*/