forked from mila-labs/express-asset-versions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
33 lines (26 loc) · 774 Bytes
/
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
var fs = require('fs')
, path = require('path')
, cs = require('checksum');
module.exports = function(urlPrefix, rootPath) {
var cache = [];
var env = process.env.NODE_ENV;
var checksumify = function(file) {
if(cache[file]) {
return cache[file];
}
var filePath = path.join(rootPath, file)
, fileUrl = path.join(urlPrefix, file).replace(/\\/g, '/');
if(!fs.existsSync(filePath)) {
return fileUrl;
}
var data = fs.readFileSync(filePath);
cache[file] = fileUrl + '?' + cs(data).substr(0, 10);
return cache[file];
};
return function(req, res, next) {
res.locals.asset = function(file, prodFile) {
return checksumify((prodFile && env === 'production') ? prodFile : file);
};
next();
};
};