-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfs.js
80 lines (65 loc) · 1.92 KB
/
fs.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
var glob = require('glob'),
path = require('path'),
fs = require('fs'),
_ = require('lodash');
module.exports = {
load: function (options, callback) {
if (arguments.length === 1 && typeof options === 'function') {
callback = options;
options = {};
}
options = _.extend({
path: 'locales/__lng__/__ns__.json',
baseDir: process.cwd()
}, options);
var datastore = {};
var glb = options.path.replace('__lng__', '[a-zA-Z\-_]*').replace('__ns__', '[a-zA-Z\-_]*'),
rgx = options.path.replace('__lng__', '([a-zA-Z\-_]*)').replace('__ns__', '([a-zA-Z\-_]*)');
glb = path.resolve(options.baseDir, glb);
rgx = new RegExp(rgx);
glob(glb, function (err, files) {
if (err) { return callback(err); }
var count = files.length;
if (files.length === 0) {
return callback(null, datastore);
}
function checkDone() {
count--;
if (count === 0) {
callback(null, datastore);
}
}
files.forEach(function (file) {
var parts = file.match(rgx).slice(1),
src = options.path.match(rgx).slice(1);
var lng, ns;
parts.forEach(function (fragment, i) {
if (src[i]) {
if (src[i] === '__lng__') {
lng = fragment;
} else if (src[i] === '__ns__') {
ns = fragment;
}
}
});
if (lng && ns) {
fs.readFile(path.resolve(options.baseDir, file), function (err, buffer) {
if (err) {
checkDone();
} else {
try {
datastore[lng] = datastore[lng] || {};
datastore[lng][ns] = JSON.parse(buffer.toString());
checkDone();
} catch(e) {
checkDone();
}
}
});
} else {
checkDone();
}
});
});
}
};