UNPKG

1.09 kBJavaScriptView Raw
1// @flow strict-local
2
3import type {Readable} from 'stream';
4import type {FileSystem} from '@parcel/fs';
5
6import crypto from 'crypto';
7import {objectSortedEntriesDeep} from './collection';
8
9type StringHashEncoding = 'hex' | 'latin1' | 'binary' | 'base64';
10
11export function md5FromString(
12 string: string | Buffer,
13 encoding: StringHashEncoding = 'hex'
14): string {
15 return crypto
16 .createHash('md5')
17 .update(string)
18 .digest(encoding);
19}
20
21export function md5FromReadableStream(stream: Readable): Promise<string> {
22 return new Promise((resolve, reject) => {
23 stream
24 .pipe(crypto.createHash('md5').setEncoding('hex'))
25 .on('finish', function() {
26 resolve(this.read());
27 })
28 .on('error', reject);
29 });
30}
31
32export function md5FromObject(
33 obj: {+[string]: mixed},
34 encoding: StringHashEncoding = 'hex'
35): string {
36 return md5FromString(JSON.stringify(objectSortedEntriesDeep(obj)), encoding);
37}
38
39export function md5FromFilePath(
40 fs: FileSystem,
41 filePath: string
42): Promise<string> {
43 return md5FromReadableStream(fs.createReadStream(filePath));
44}