or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-object-hash

Generate hashes from javascript objects in node and the browser.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/object-hash@3.0.x

To install, run

npx @tessl/cli install tessl/npm-object-hash@3.0.0

index.mddocs/

Object Hash

Object Hash is a robust JavaScript library that generates consistent hash values from any JavaScript object, value, or data structure. It works in both Node.js and browser environments, supporting multiple hash algorithms and extensive configuration options for deterministic object serialization.

Package Information

  • Package Name: object-hash
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install object-hash

Core Imports

const hash = require('object-hash');

ES6/ESM:

import hash from 'object-hash';

Browser (UMD):

<script src="object_hash.js"></script>
<script>
  const hashValue = objectHash.sha1({foo: 'bar'});
</script>

Basic Usage

const hash = require('object-hash');

// Basic object hashing
const obj = { name: 'John', age: 30, city: 'New York' };
const hashValue = hash(obj);
console.log(hashValue); // => "67b69634f9880a282c14a0f0cb7ba20cf5d677e9"

// Hash arrays
const arr = [1, 2, 2.718, 3.14159];
const arrayHash = hash(arr);
console.log(arrayHash); // => "136b9b88375971dff9f1af09d7356e3e04281951"

// Different algorithms and encodings
const md5Hash = hash(obj, { algorithm: 'md5', encoding: 'base64' });
console.log(md5Hash); // => "6rkWaaDiG3NynWw4svGH7g=="

Capabilities

Main Hash Function

Generate a hash from any object or type with extensive configuration options.

/**
 * Generate a hash from any object or type
 * @param {any} object - Value to hash
 * @param {HashOptions} options - Optional hashing configuration
 * @returns {string} Hash value
 */
function hash(object, options);

interface HashOptions {
  /** Hash algorithm: 'sha1', 'md5', 'passthrough', or any crypto.getHashes() result (default: 'sha1') */
  algorithm?: string;
  /** Hash encoding: 'buffer', 'hex', 'binary', 'base64' (default: 'hex') */
  encoding?: string;
  /** Hash object keys only, ignore values (default: false) */
  excludeValues?: boolean;
  /** Ignore unknown object types (default: false) */
  ignoreUnknown?: boolean;
  /** Optional function that replaces values before hashing */
  replacer?: (value: any) => any;
  /** Consider function properties when hashing (default: true) */
  respectFunctionProperties?: boolean;
  /** Consider 'name' property of functions for hashing (default: true) */
  respectFunctionNames?: boolean;
  /** Respect special type attributes (.prototype, .__proto__, .constructor) (default: true) */
  respectType?: boolean;
  /** Sort all arrays before hashing (default: false) */
  unorderedArrays?: boolean;
  /** Sort Set and Map instances before hashing (default: true) */
  unorderedSets?: boolean;
  /** Sort objects before hashing (default: true) */
  unorderedObjects?: boolean;
  /** Optional function for excluding specific keys from hashing */
  excludeKeys?: (key: string) => boolean;
}

Usage Examples:

const hash = require('object-hash');

// Basic usage with default SHA-1
const basicHash = hash({ foo: 'bar', baz: 42 });

// Custom algorithm and encoding
const customHash = hash(
  { user: 'alice', role: 'admin' },
  { algorithm: 'md5', encoding: 'base64' }
);

// Exclude specific keys
const filteredHash = hash(
  { name: 'John', password: 'secret', email: 'john@example.com' },
  { 
    excludeKeys: function(key) {
      return key === 'password';
    }
  }
);

// Hash only keys, ignore values
const keysOnlyHash = hash(
  { name: 'Alice', age: 25 },
  { excludeValues: true }
);

// Unordered arrays (sort before hashing)
const unorderedHash = hash(
  { tags: ['javascript', 'nodejs', 'hash'] },
  { unorderedArrays: true }
);

SHA-1 Hash

Hash using the SHA-1 algorithm (equivalent to default behavior).

/**
 * Hash using the SHA-1 algorithm
 * @param {any} object - Value to hash
 * @returns {string} SHA-1 hash value
 */
hash.sha1(object);

Usage Example:

const sha1Hash = hash.sha1({ data: 'example' });
// Equivalent to: hash({ data: 'example' }, { algorithm: 'sha1' })

Keys Hash

Hash object keys using SHA-1, ignoring values.

/**
 * Hash object keys using SHA-1, values ignored
 * @param {any} object - Value to hash
 * @returns {string} Hash of keys only
 */
hash.keys(object);

Usage Example:

const user1 = { name: 'Alice', age: 25, city: 'NYC' };
const user2 = { name: 'Bob', age: 30, city: 'LA' };

const keysHash1 = hash.keys(user1);
const keysHash2 = hash.keys(user2);
// Both return the same hash since they have the same keys

MD5 Hash

Hash using the MD5 algorithm.

/**
 * Hash using the MD5 algorithm
 * @param {any} object - Value to hash
 * @returns {string} MD5 hash value
 */
hash.MD5(object);

Usage Example:

const md5Hash = hash.MD5({ data: 'example' });
// Equivalent to: hash({ data: 'example' }, { algorithm: 'md5' })

MD5 Keys Hash

Hash object keys using MD5, ignoring values.

/**
 * Hash object keys using MD5, values ignored
 * @param {any} object - Value to hash
 * @returns {string} MD5 hash of keys only
 */
hash.keysMD5(object);

Usage Example:

const structure = { id: 1, name: 'test', metadata: { created: Date.now() }};
const structureHash = hash.keysMD5(structure);
// Returns MD5 hash of the object structure (keys only)

Stream Writing

Write the information that would otherwise have been hashed to a stream.

/**
 * Write the information that would otherwise have been hashed to a stream
 * @param {any} object - Value to serialize
 * @param {HashOptions} options - Optional hashing configuration (optional)
 * @param {Stream} stream - A stream to write the serialization to
 * @returns {void}
 */
hash.writeToStream(object, options, stream);

// Alternative signature when options are omitted:
hash.writeToStream(object, stream);

Usage Example:

const hash = require('object-hash');

// Write to stdout
hash.writeToStream(
  { foo: 'bar', num: 42 }, 
  { respectType: false }, 
  process.stdout
);
// Outputs: "object:foo:string:barnum:number:42"

// Write to a custom stream
const fs = require('fs');
const writeStream = fs.createWriteStream('./output.txt');
hash.writeToStream({ data: 'example' }, writeStream);

Supported Data Types

Object Hash can handle all JavaScript types including:

  • Primitives: string, number, boolean, null, undefined, symbol, bigint
  • Objects: plain objects, arrays, dates, regular expressions, errors, functions
  • Typed Arrays: Uint8Array, Int8Array, Uint16Array, Int16Array, Uint32Array, Int32Array, Float32Array, Float64Array, Uint8ClampedArray, ArrayBuffer
  • Collections: Set, Map
  • Browser Types: File, URL, Blob (with limitations)
  • Node.js Types: Buffer, process objects, timers, streams, and other Node.js internals

Error Handling

The library throws errors in the following situations:

  • Missing object argument: Error('Object argument required.')
  • Unsupported algorithm: Error('Algorithm "xyz" not supported. supported values: sha1, md5, ...')
  • Unsupported encoding: Error('Encoding "xyz" not supported. supported values: buffer, hex, binary, base64')
  • Unknown object types: Error('Unknown object type "xyz"') (unless ignoreUnknown: true)
  • Blob objects: Error('Hashing Blob objects is currently not supported...') (unless using replacer or ignoreUnknown)

Available Algorithms

  • 'sha1' (default) - SHA-1 algorithm (not cryptographically secure)
  • 'md5' - MD5 algorithm (not cryptographically secure)
  • 'passthrough' - Returns serialization string instead of hash
  • Any crypto.getHashes() algorithm - Any algorithm supported by Node.js crypto module

Note: SHA-1 and MD5 are not considered cryptographically secure. Use stronger algorithms if cryptographic security is required.

Available Encodings

  • 'hex' (default) - Hexadecimal string
  • 'base64' - Base64 encoded string
  • 'binary' - Binary string
  • 'buffer' - Returns Buffer object (Node.js only)

Configuration Examples

const hash = require('object-hash');

// Cryptographically secure hash
const secureHash = hash(data, { algorithm: 'sha256' });

// Deterministic array hashing (order-independent)
const deterministicHash = hash(
  { items: [3, 1, 2] },
  { unorderedArrays: true }
);

// Function-aware hashing
const fnHash = hash(
  { handler: function myHandler() { return true; } },
  { 
    respectFunctionNames: true,
    respectFunctionProperties: true 
  }
);

// Custom serialization with replacer
const customHash = hash(data, {
  replacer: function(value) {
    if (value instanceof Date) {
      return value.toISOString();
    }
    return value;
  }
});

// Ignore unknown types instead of throwing
const safeHash = hash(data, { ignoreUnknown: true });