/
map-path.js
86 lines (69 loc) · 1.79 KB
/
map-path.js
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
var url = require('url')
, async = require('async')
, crypto = require('crypto')
, fs = require('fs')
, path = require('path')
, _ = require('lodash')
, walker = require('walker')
module.exports = function(dirPath, params, callback) {
var
files = []
if ((callback === undefined) && (typeof params === 'function')) {
callback = params
}
var options = _.extend({
basePath: '',
hash: hash
}, params)
if (!dirPath) {
return callback(new Error('Path is required'))
}
// trim trailing slash
if (dirPath.substring(dirPath.length - 1) === '/') {
dirPath = dirPath.slice(0, -1);
}
function hash(filename, callback) {
var
md5sum = crypto.createHash('md5'),
s = fs.ReadStream(filename)
s.on('data', function(d) {
md5sum.update(d)
})
s.on('end', function() {
callback(undefined, md5sum.digest('hex'))
})
}
function makeHashMap (callback) {
var hashMap = Object.create(null)
async.forEach(files, function(filename, fileCallback) {
hash(filename, function(error, fileHash) {
var
urlPath = path.normalize('/' + filename.substring(dirPath.length + 1)).replace(/\\/g, '/'),
pos = urlPath.lastIndexOf('/')
hashMap[urlPath] =
urlPath.substring(0, pos) + '/' + fileHash +
urlPath.substring(pos) || url
fileCallback(error)
})
}, function(error) {
if (error) {
return callback(error)
}
callback(undefined, hashMap)
})
}
if (options.fileList) {
for (var i in options.fileList) {
files.push(options.fileList[i])
}
makeHashMap(callback)
return
}
walker(dirPath)
.on('file', function(filename) {
files.push(filename)
})
.on('end', function() {
makeHashMap(callback)
})
}