Generate hashes from javascript objects in node and the browser.
npx @tessl/cli install tessl/npm-object-hash@3.0.00
# Object Hash
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: object-hash
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install object-hash`
10
11
## Core Imports
12
13
```javascript
14
const hash = require('object-hash');
15
```
16
17
ES6/ESM:
18
19
```javascript
20
import hash from 'object-hash';
21
```
22
23
Browser (UMD):
24
25
```html
26
<script src="object_hash.js"></script>
27
<script>
28
const hashValue = objectHash.sha1({foo: 'bar'});
29
</script>
30
```
31
32
## Basic Usage
33
34
```javascript
35
const hash = require('object-hash');
36
37
// Basic object hashing
38
const obj = { name: 'John', age: 30, city: 'New York' };
39
const hashValue = hash(obj);
40
console.log(hashValue); // => "67b69634f9880a282c14a0f0cb7ba20cf5d677e9"
41
42
// Hash arrays
43
const arr = [1, 2, 2.718, 3.14159];
44
const arrayHash = hash(arr);
45
console.log(arrayHash); // => "136b9b88375971dff9f1af09d7356e3e04281951"
46
47
// Different algorithms and encodings
48
const md5Hash = hash(obj, { algorithm: 'md5', encoding: 'base64' });
49
console.log(md5Hash); // => "6rkWaaDiG3NynWw4svGH7g=="
50
```
51
52
## Capabilities
53
54
### Main Hash Function
55
56
Generate a hash from any object or type with extensive configuration options.
57
58
```javascript { .api }
59
/**
60
* Generate a hash from any object or type
61
* @param {any} object - Value to hash
62
* @param {HashOptions} options - Optional hashing configuration
63
* @returns {string} Hash value
64
*/
65
function hash(object, options);
66
67
interface HashOptions {
68
/** Hash algorithm: 'sha1', 'md5', 'passthrough', or any crypto.getHashes() result (default: 'sha1') */
69
algorithm?: string;
70
/** Hash encoding: 'buffer', 'hex', 'binary', 'base64' (default: 'hex') */
71
encoding?: string;
72
/** Hash object keys only, ignore values (default: false) */
73
excludeValues?: boolean;
74
/** Ignore unknown object types (default: false) */
75
ignoreUnknown?: boolean;
76
/** Optional function that replaces values before hashing */
77
replacer?: (value: any) => any;
78
/** Consider function properties when hashing (default: true) */
79
respectFunctionProperties?: boolean;
80
/** Consider 'name' property of functions for hashing (default: true) */
81
respectFunctionNames?: boolean;
82
/** Respect special type attributes (.prototype, .__proto__, .constructor) (default: true) */
83
respectType?: boolean;
84
/** Sort all arrays before hashing (default: false) */
85
unorderedArrays?: boolean;
86
/** Sort Set and Map instances before hashing (default: true) */
87
unorderedSets?: boolean;
88
/** Sort objects before hashing (default: true) */
89
unorderedObjects?: boolean;
90
/** Optional function for excluding specific keys from hashing */
91
excludeKeys?: (key: string) => boolean;
92
}
93
```
94
95
**Usage Examples:**
96
97
```javascript
98
const hash = require('object-hash');
99
100
// Basic usage with default SHA-1
101
const basicHash = hash({ foo: 'bar', baz: 42 });
102
103
// Custom algorithm and encoding
104
const customHash = hash(
105
{ user: 'alice', role: 'admin' },
106
{ algorithm: 'md5', encoding: 'base64' }
107
);
108
109
// Exclude specific keys
110
const filteredHash = hash(
111
{ name: 'John', password: 'secret', email: 'john@example.com' },
112
{
113
excludeKeys: function(key) {
114
return key === 'password';
115
}
116
}
117
);
118
119
// Hash only keys, ignore values
120
const keysOnlyHash = hash(
121
{ name: 'Alice', age: 25 },
122
{ excludeValues: true }
123
);
124
125
// Unordered arrays (sort before hashing)
126
const unorderedHash = hash(
127
{ tags: ['javascript', 'nodejs', 'hash'] },
128
{ unorderedArrays: true }
129
);
130
```
131
132
### SHA-1 Hash
133
134
Hash using the SHA-1 algorithm (equivalent to default behavior).
135
136
```javascript { .api }
137
/**
138
* Hash using the SHA-1 algorithm
139
* @param {any} object - Value to hash
140
* @returns {string} SHA-1 hash value
141
*/
142
hash.sha1(object);
143
```
144
145
**Usage Example:**
146
147
```javascript
148
const sha1Hash = hash.sha1({ data: 'example' });
149
// Equivalent to: hash({ data: 'example' }, { algorithm: 'sha1' })
150
```
151
152
### Keys Hash
153
154
Hash object keys using SHA-1, ignoring values.
155
156
```javascript { .api }
157
/**
158
* Hash object keys using SHA-1, values ignored
159
* @param {any} object - Value to hash
160
* @returns {string} Hash of keys only
161
*/
162
hash.keys(object);
163
```
164
165
**Usage Example:**
166
167
```javascript
168
const user1 = { name: 'Alice', age: 25, city: 'NYC' };
169
const user2 = { name: 'Bob', age: 30, city: 'LA' };
170
171
const keysHash1 = hash.keys(user1);
172
const keysHash2 = hash.keys(user2);
173
// Both return the same hash since they have the same keys
174
```
175
176
### MD5 Hash
177
178
Hash using the MD5 algorithm.
179
180
```javascript { .api }
181
/**
182
* Hash using the MD5 algorithm
183
* @param {any} object - Value to hash
184
* @returns {string} MD5 hash value
185
*/
186
hash.MD5(object);
187
```
188
189
**Usage Example:**
190
191
```javascript
192
const md5Hash = hash.MD5({ data: 'example' });
193
// Equivalent to: hash({ data: 'example' }, { algorithm: 'md5' })
194
```
195
196
### MD5 Keys Hash
197
198
Hash object keys using MD5, ignoring values.
199
200
```javascript { .api }
201
/**
202
* Hash object keys using MD5, values ignored
203
* @param {any} object - Value to hash
204
* @returns {string} MD5 hash of keys only
205
*/
206
hash.keysMD5(object);
207
```
208
209
**Usage Example:**
210
211
```javascript
212
const structure = { id: 1, name: 'test', metadata: { created: Date.now() }};
213
const structureHash = hash.keysMD5(structure);
214
// Returns MD5 hash of the object structure (keys only)
215
```
216
217
### Stream Writing
218
219
Write the information that would otherwise have been hashed to a stream.
220
221
```javascript { .api }
222
/**
223
* Write the information that would otherwise have been hashed to a stream
224
* @param {any} object - Value to serialize
225
* @param {HashOptions} options - Optional hashing configuration (optional)
226
* @param {Stream} stream - A stream to write the serialization to
227
* @returns {void}
228
*/
229
hash.writeToStream(object, options, stream);
230
231
// Alternative signature when options are omitted:
232
hash.writeToStream(object, stream);
233
```
234
235
**Usage Example:**
236
237
```javascript
238
const hash = require('object-hash');
239
240
// Write to stdout
241
hash.writeToStream(
242
{ foo: 'bar', num: 42 },
243
{ respectType: false },
244
process.stdout
245
);
246
// Outputs: "object:foo:string:barnum:number:42"
247
248
// Write to a custom stream
249
const fs = require('fs');
250
const writeStream = fs.createWriteStream('./output.txt');
251
hash.writeToStream({ data: 'example' }, writeStream);
252
```
253
254
## Supported Data Types
255
256
Object Hash can handle all JavaScript types including:
257
258
- **Primitives**: string, number, boolean, null, undefined, symbol, bigint
259
- **Objects**: plain objects, arrays, dates, regular expressions, errors, functions
260
- **Typed Arrays**: Uint8Array, Int8Array, Uint16Array, Int16Array, Uint32Array, Int32Array, Float32Array, Float64Array, Uint8ClampedArray, ArrayBuffer
261
- **Collections**: Set, Map
262
- **Browser Types**: File, URL, Blob (with limitations)
263
- **Node.js Types**: Buffer, process objects, timers, streams, and other Node.js internals
264
265
## Error Handling
266
267
The library throws errors in the following situations:
268
269
- **Missing object argument**: `Error('Object argument required.')`
270
- **Unsupported algorithm**: `Error('Algorithm "xyz" not supported. supported values: sha1, md5, ...')`
271
- **Unsupported encoding**: `Error('Encoding "xyz" not supported. supported values: buffer, hex, binary, base64')`
272
- **Unknown object types**: `Error('Unknown object type "xyz"')` (unless `ignoreUnknown: true`)
273
- **Blob objects**: `Error('Hashing Blob objects is currently not supported...')` (unless using `replacer` or `ignoreUnknown`)
274
275
## Available Algorithms
276
277
- **'sha1'** (default) - SHA-1 algorithm (not cryptographically secure)
278
- **'md5'** - MD5 algorithm (not cryptographically secure)
279
- **'passthrough'** - Returns serialization string instead of hash
280
- **Any crypto.getHashes() algorithm** - Any algorithm supported by Node.js crypto module
281
282
**Note**: SHA-1 and MD5 are not considered cryptographically secure. Use stronger algorithms if cryptographic security is required.
283
284
## Available Encodings
285
286
- **'hex'** (default) - Hexadecimal string
287
- **'base64'** - Base64 encoded string
288
- **'binary'** - Binary string
289
- **'buffer'** - Returns Buffer object (Node.js only)
290
291
## Configuration Examples
292
293
```javascript
294
const hash = require('object-hash');
295
296
// Cryptographically secure hash
297
const secureHash = hash(data, { algorithm: 'sha256' });
298
299
// Deterministic array hashing (order-independent)
300
const deterministicHash = hash(
301
{ items: [3, 1, 2] },
302
{ unorderedArrays: true }
303
);
304
305
// Function-aware hashing
306
const fnHash = hash(
307
{ handler: function myHandler() { return true; } },
308
{
309
respectFunctionNames: true,
310
respectFunctionProperties: true
311
}
312
);
313
314
// Custom serialization with replacer
315
const customHash = hash(data, {
316
replacer: function(value) {
317
if (value instanceof Date) {
318
return value.toISOString();
319
}
320
return value;
321
}
322
});
323
324
// Ignore unknown types instead of throwing
325
const safeHash = hash(data, { ignoreUnknown: true });
326
```