This repository was archived by the owner on Jul 31, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.js
More file actions
67 lines (53 loc) · 1.22 KB
/
data.js
File metadata and controls
67 lines (53 loc) · 1.22 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
var utils = require('./utils');
var fs = require('fs');
var path = require('path');
var globby = require('globby');
var cachedDataFiles = {};
/**
* Load a JSON data file, avoiding reading and parsing the file if it has not
* changed.
*/
var loadDataFile = function(file, cb) {
var cached = cachedDataFiles[file];
fs.stat(file, function(err, stat) {
if(! stat) return cb(null, null);
if(! cached || stat.mtime > cached.mtime) {
if(! cached) {
cached = cachedDataFiles[file] = {};
}
cached.mtime = stat.mtime;
fs.readFile(file, 'utf8', function(err2, data) {
if(err2) return cb(err2);
cached.data = JSON.parse(data);
cb(null, cached.data);
});
return;
}
cb(null, cached.data);
});
};
/**
* Load all of the data files we have.
*/
module.exports.loadAll = function(obj, cb) {
if(! obj) {
obj = {};
}
globby(utils.srcGlob('data'))
.then(function(files) {
if(files.length === 0) cb(null, obj);
var count = files.length;
files.forEach(function(file) {
loadDataFile(file, function(err, data) {
if(err) {
count = -1;
cb(err);
}
obj[path.basename(file, '.json')] = data;
if(--count === 0) {
cb(null, obj);
}
});
});
});
};