UNPKG

1.19 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.on('error', err => {
24 reject(err);
25 });
26 stream
27 .pipe(crypto.createHash('md5').setEncoding('hex'))
28 .on('finish', function() {
29 resolve(this.read());
30 })
31 .on('error', err => {
32 reject(err);
33 });
34 });
35}
36
37export function md5FromObject(
38 obj: {+[string]: mixed, ...},
39 encoding: StringHashEncoding = 'hex',
40): string {
41 return md5FromString(JSON.stringify(objectSortedEntriesDeep(obj)), encoding);
42}
43
44export function md5FromFilePath(
45 fs: FileSystem,
46 filePath: string,
47): Promise<string> {
48 return md5FromReadableStream(fs.createReadStream(filePath));
49}