forked from alexkwolfe/json-fs-store
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
114 lines (94 loc) · 2.55 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
var async = require('async'),
fs = require('graceful-fs'),
path = require('path'),
uuid = require('node-uuid'),
mkdirp = require('mkdirp');
module.exports = function(dir) {
dir = dir || path.join(process.cwd(), 'store');
return {
// store in this directory
dir: dir,
// list all stored objects by reading the file system
list: function(cb) {
var self = this;
var action = function(err) {
if (err) return cb(err);
readdir(dir, function(err, files) {
if (err) return cb(err);
files = files.filter(function(f) { return f.substr(-5) === ".json"; });
var fileLoaders = files.map(function(f) {
return function(cb) {
loadFile(f, cb);
};
});
async.parallel(fileLoaders, function(err, objs) {
if (err) return cb(err);
sort(objs, cb);
});
})
};
mkdirp(dir, action);
},
// store an object to file
add: function(obj, cb) {
var action = function(err) {
if (err) return cb(err);
var json;
try {
json = JSON.stringify(obj, null, 2);
}
catch (e) {
return cb(e);
}
obj.id = obj.id || uuid.v4();
fs.writeFile(path.join(dir, obj.id + '.json'), json, 'utf8', function(err) {
if (err) return cb(err);
cb();
});
};
mkdirp(dir, action);
},
// delete an object's file
remove: function(obj, cb) {
var action = function(err) {
if (err) return cb(err);
fs.unlink(path.join(dir, obj.id + '.json'), function(err) {
cb(err);
});
}
mkdirp(dir, action);
},
// load an object from file
load: function(id, cb) {
mkdirp(dir, function(err) {
if (err) return cb(err);
loadFile(path.join(dir, id + '.json'), cb);
})
}
}
};
var readdir = function(dir, cb) {
fs.readdir(dir, function(err, files) {
if (err) return cb(err);
files = files.map(function(f) {
return path.join(dir, f);
});
cb(null, files);
});
};
var loadFile = function(f, cb) {
fs.readFile(f, 'utf8', function(err, code) {
if (err) return cb("error loading file" + err);
try {
cb(null, JSON.parse(code));
}
catch (e) {
cb("Error parsing " + f + ": " + e);
}
});
};
var sort = function(objs, cb) {
async.sortBy(objs, function(obj, cb) {
cb(null, obj.name || '');
}, cb);
};