Security News
JavaScript Leaders Demand Oracle Release the JavaScript Trademark
In an open letter, JavaScript community leaders urge Oracle to give up the JavaScript trademark, arguing that it has been effectively abandoned through nonuse.
deterministic-object-hash
Advanced tools
The deterministic-object-hash npm package is used to create consistent and deterministic hashes for JavaScript objects. This is particularly useful for scenarios where you need to ensure that the same object always produces the same hash, regardless of the order of its properties.
Basic Hashing
This feature allows you to generate a deterministic hash for a given object. The order of properties in the object does not affect the hash value.
const deterministicHash = require('deterministic-object-hash');
const obj = { b: 2, a: 1 };
const hash = deterministicHash(obj);
console.log(hash);
Custom Hashing Algorithm
This feature allows you to specify a custom hashing algorithm. In this example, the 'sha256' algorithm is used to generate the hash.
const deterministicHash = require('deterministic-object-hash');
const obj = { b: 2, a: 1 };
const options = { algorithm: 'sha256' };
const hash = deterministicHash(obj, options);
console.log(hash);
Hashing with Custom Sort Function
This feature allows you to provide a custom sort function to determine the order of properties before hashing. This can be useful for more complex sorting requirements.
const deterministicHash = require('deterministic-object-hash');
const obj = { b: 2, a: 1 };
const options = { sort: (a, b) => a.localeCompare(b) };
const hash = deterministicHash(obj, options);
console.log(hash);
The object-hash package generates hashes for JavaScript objects. It offers various hashing algorithms and options for customization. Compared to deterministic-object-hash, object-hash provides more flexibility in terms of hashing algorithms and options but may not guarantee the same level of determinism in all cases.
The json-stable-stringify package is used to stringify JavaScript objects in a deterministic way by sorting the properties. This can be used in conjunction with a hashing function to achieve similar results to deterministic-object-hash. However, it requires an additional step to hash the stringified output.
The built-in crypto module in Node.js can be used to create hashes for strings. When combined with a stable stringification method like json-stable-stringify, it can achieve similar functionality to deterministic-object-hash. However, it requires more manual setup and does not provide a single, cohesive API for deterministic object hashing.
A deterministic object hashing algorithm for Node.js.
Using JSON.stringify
on two objects that are deeply equal does not lead to the same output string. Instead the keys are ordered in the same order that they were added. This leads to two objects that are deeply equal being hashed to different values.
import { createHash } from "crypto";
import { isEqual } from "lodash";
const obj1: Record<string, string> = {};
obj1['a'] = 'x';
obj1['b'] = 'y';
obj1['c'] = 'z';
const obj2: Record<string, string> = {};
obj2['c'] = 'z';
obj2['b'] = 'y';
obj2['a'] = 'x';
isEqual(obj1, obj2);
// -> true
const string1 = JSON.stringify(obj1);
// -> {"a":"x","b":"y","c":"z"}
const string2 = JSON.stringify(obj2);
// -> {"c":"z","b":"y","a":"x"}
createHash('sha1').update(string1).digest('hex');
// -> ff75fe071d236ce309c15d5636ecaa86c0519ebc
createHash('sha1').update(string2).digest('hex');
// -> 2e53bac865f7be77c8e10cd86d737fbbf259ed37
Pass a value and receive a deterministic hash of the value.
import deterministicHash from 'deterministic-object-hash';
const objA = { a: 'x', arr: [1,2,3,4], b: 'y' };
const objB = { b: 'y', a: 'x', arr: [1,2,3,4] };
deterministicHash({
c: [ objA, objB ],
b: objA,
e: objB,
f: ()=>{ Math.random(); },
g: Symbol('Unique identity'),
h: new Error('AHHH')
});
// -> 4c57bcb76498dca7b98ef9747c8f1e7f10c30388
deterministicHash({
h: new Error('AHHH'),
e: objB,
g: Symbol('Unique identity'),
b: objA,
f: ()=>{ Math.random(); },
c: [ objA, objB ]
});
// -> 4c57bcb76498dca7b98ef9747c8f1e7f10c30388
A hash algorithm can be passed as the second argument. This takes any value that is valid for crypto.createHash
. The default is sha1
.
A digest format can be passed as the third argument. This takes any value that is valid for Hash.digest
. The default is hex
.
deterministicHash('value', 'sha1');
// -> efede6000ad4e1ff258a38866c71aa351d3c01f6
deterministicHash('value', 'sha256', 'hex');
// -> a0b7821a11db531982044ca5ca2e788e2d749d6b696cd3aa4172342f584f2ee1
deterministicHash('value', 'sha512', 'base64');
// -> 514CuHw/31qqUH2waqaqhKSMvLYH/YdZeRI4QqDBwhKbUk0/3mxhv4NUubXIl5Dm2k0VpU6ZZkmunEb10RngfQ==
String | Number |
Boolean | Function |
Plain Objects | Symbol |
undefined | null |
Infinity | NaN |
BigInt | Array |
Classes/Inheritance | Errors |
Date | RegExp |
Map | Set |
Int8Array | Uint8Array |
Int16Array | Uint16Array |
Int32Array | Uint32Array |
Float32Array | Float64Array |
BigInt64Array | BigUint64Array |
Uint8ClampedArray | globalThis |
ArrayBuffer | SharedArrayBuffer |
WeakMap | WeakSet |
Atomics | DataView |
Promises | Reflect |
Proxy |
Due to their nature, WeakSet and WeakMap are not enumerable. As a result there is no way to know what is in a WeakSet/WeakMap unless we are told.
Currently this has only been tested on Node.js 16.3.x
. More tests are to come and this section will be updated as I test them.
FAQs
A deterministic object hashing algorithm for Node.js.
The npm package deterministic-object-hash receives a total of 197,642 weekly downloads. As such, deterministic-object-hash popularity was classified as popular.
We found that deterministic-object-hash demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
In an open letter, JavaScript community leaders urge Oracle to give up the JavaScript trademark, arguing that it has been effectively abandoned through nonuse.
Security News
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
Security News
Floating dependency ranges in npm can introduce instability and security risks into your project by allowing unverified or incompatible versions to be installed automatically, leading to unpredictable behavior and potential conflicts.