-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathdirsum.js
More file actions
96 lines (82 loc) · 2.48 KB
/
dirsum.js
File metadata and controls
96 lines (82 loc) · 2.48 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
var crypto = require('crypto');
var fs = require('fs');
function _summarize(method, hashes) {
var keys = Object.keys(hashes);
keys.sort();
var obj = {};
obj.files = hashes;
var hash = crypto.createHash(method);
for (var i = 0; i < keys.length; i++) {
if (typeof(hashes[keys[i]]) === 'string') {
hash.update(hashes[keys[i]]);
} else if (typeof(hashes[keys[i]]) === 'object') {
hash.update(hashes[keys[i]].hash);
} else {
console.error('Unknown type found in hash: ' + typeof(hashes[keys[i]]));
}
}
obj.hash = hash.digest('hex');
return obj;
}
function digest(root, method, callback) {
if (!root || typeof(root) !== 'string') {
throw new TypeError('root is required (string)');
}
if (method) {
if (typeof(method) === 'string') {
// NO-OP
} else if (typeof(method) === 'function') {
callback = method;
method = 'md5';
} else {
throw new TypeError('hash must be a string');
}
} else {
throw new TypeError('callback is required (function)');
}
if (!callback) {
throw new TypeError('callback is required (function)');
}
var hashes = {};
fs.readdir(root, function(err, files) {
if (err) return callback(err);
if (files.length === 0) {
return callback(undefined, {hash: '', files: {}});
}
var hashed = 0;
files.forEach(function(f) {
var path = root + '/' + f;
fs.stat(path, function(err, stats) {
if (err) return callback(err);
if (stats.isDirectory()) {
return digest(path, method, function(err, hash) {
if (err) return hash;
hashes[f] = hash;
if (++hashed >= files.length) {
return callback(undefined, _summarize(method, hashes));
}
});
} else if (stats.isFile()) {
fs.readFile(path, 'utf8', function(err, data) {
if (err) return callback(err);
var hash = crypto.createHash(method);
hash.update(data);
hashes[f] = hash.digest('hex');
if (++hashed >= files.length) {
return callback(undefined, _summarize(method, hashes));
}
});
} else {
console.error('Skipping hash of %s', f);
if (++hashed > files.length) {
return callback(undefined, _summarize(method, hashes));
}
}
});
});
});
}
module.exports = {
digest: digest
};