-
Notifications
You must be signed in to change notification settings - Fork 0
/
json-reader.js
93 lines (71 loc) · 1.97 KB
/
json-reader.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
var readJSON = require('./read-json');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
util.inherits(JSONReader, EventEmitter);
exports.readJSONFiles = readJSONFiles;
exports.readJSONFilesForgiving = readJSONFilesForgiving;
exports.JSONReader = JSONReader;
function readJSONFiles(list, callback) {
var results = {};
var reader = new JSONReader(list);
reader.on('error', function (error, filepath) {
reader.abort();
callback(error);
});
reader.on('data', function (data, filepath) {
results[filepath] = data;
});
reader.on('end', function () {
callback(null, results);
});
}
function readJSONFilesForgiving(list, callback) {
var warnings = {};
var results = {};
var reader = new JSONReader(list);
reader.on('error', function (error, filepath) {
warnings[filepath] = error;
});
reader.on('data', function (data, filepath) {
results[filepath] = data;
});
reader.on('end', function () {
callback(null, results, warnings);
});
}
function JSONReader(list) {
var self = this;
EventEmitter.call(self);
self.aborted = false;
self.abort = _readerAbort;
process.nextTick(function () {
_readerStart(list, self);
});
}
function _readerAbort() {
this.aborted = true;
this.emit('abort');
}
function _readerStart(list, reader) {
var pending = 0;
if (reader.aborted) return;
if (list.length) {
list.forEach(eachfile);
} else {
reader.emit('end');
}
function eachfile(filepath) {
readJSON(filepath, (pending++, onread));
function onread(error, result) {
if (reader.aborted) return;
if (error) {
reader.emit('error', error, filepath);
} else {
reader.emit('data', result, filepath);
}
if ( ! --pending) {
reader.emit('end');
}
}
}
}