451cdc97fa473e94d3fb6f59b4713c276fbef7cc.svn-base
1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
'use strict';
const fs = require('fs');
const crypto = require('crypto');
const isStream = require('is-stream');
const hasha = (input, opts) => {
opts = opts || {};
let outputEncoding = opts.encoding || 'hex';
if (outputEncoding === 'buffer') {
outputEncoding = undefined;
}
const hash = crypto.createHash(opts.algorithm || 'sha512');
const update = buf => {
const inputEncoding = typeof buf === 'string' ? 'utf8' : undefined;
hash.update(buf, inputEncoding);
};
if (Array.isArray(input)) {
input.forEach(update);
} else {
update(input);
}
return hash.digest(outputEncoding);
};
hasha.stream = opts => {
opts = opts || {};
let outputEncoding = opts.encoding || 'hex';
if (outputEncoding === 'buffer') {
outputEncoding = undefined;
}
const stream = crypto.createHash(opts.algorithm || 'sha512');
stream.setEncoding(outputEncoding);
return stream;
};
hasha.fromStream = (stream, opts) => {
if (!isStream(stream)) {
return Promise.reject(new TypeError('Expected a stream'));
}
opts = opts || {};
return new Promise((resolve, reject) => {
stream
.on('error', reject)
.pipe(hasha.stream(opts))
.on('error', reject)
.on('finish', function () {
resolve(this.read());
});
});
};
hasha.fromFile = (fp, opts) => hasha.fromStream(fs.createReadStream(fp), opts);
hasha.fromFileSync = (fp, opts) => hasha(fs.readFileSync(fp), opts);
module.exports = hasha;