forked from keithamus/hashmark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
85 lines (83 loc) · 3.04 KB
/
index.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
'use strict';
var Stream = require('stream');
var crypto = require('crypto');
var EventEmitter = require('events').EventEmitter;
var fs = require('fs');
var path = require('path');
function parseFilePattern(pattern, fileName, hash) {
pattern = pattern || '';
fileName = fileName || '';
var ext = path.extname(fileName);
return pattern
.replace('{dir}', path.dirname(fileName))
.replace('{hash}', hash)
.replace('{name}', path.basename(fileName, ext))
.replace('{ext}', ext);
}
module.exports = function hashmark(contents, options, callback) {
contents = (contents instanceof Array) ? contents : [contents];
var mapEvents = new EventEmitter();
var fileCount = contents.length;
var map = {};
if (!callback && typeof options === 'function') {
callback = options;
options = {};
}
options.digest = options.digest || 'sha256';
options.length = options.length || 0;
if (callback) {
mapEvents.on('error', callback);
mapEvents.on('end', function (map) {
callback(null, map);
});
}
contents.map(function (contents) {
if (contents instanceof Stream.Readable) {
contents.fileName = contents.fileName || '<anonymous>';
return contents;
} else {
var stream = fs.createReadStream(contents);
stream.fileName = contents;
return stream;
}
}).forEach(function (stream) {
var contents = new Buffer('');
var hash = crypto.createHash(options.digest);
hash.on('error', mapEvents.emit.bind(mapEvents, 'error'));
stream.on('error', mapEvents.emit.bind(mapEvents, 'error'));
if (options.pattern) {
var contentStream = new Stream.PassThrough();
contentStream.on('error', mapEvents.emit.bind(mapEvents, 'error'));
contentStream.on('data', function (chunk) {
contents = Buffer.concat([contents, chunk]);
});
stream.pipe(contentStream);
}
stream.on('end', function () {
var digest = hash.digest('hex');
var strippedFileName = stream.fileName.replace(/[\/.]/g, '_');
if (options.length) {
digest = digest.slice(0, options.length);
}
if (options.pattern) {
var fileName = parseFilePattern(options.pattern, stream.fileName, digest);
fs.writeFile(fileName, contents, function (err) {
if (err) {
return mapEvents.emit('error', err);
}
mapEvents.emit('file', strippedFileName, fileName);
});
} else {
mapEvents.emit('file', strippedFileName, digest);
}
});
stream.pipe(hash, { end: false });
});
return mapEvents.on('file', function (fileName, newFileName) {
map[fileName] = newFileName;
fileCount--;
if (fileCount === 0) {
mapEvents.emit('end', map);
}
});
};