-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdata_handler.js
39 lines (38 loc) · 1.13 KB
/
data_handler.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
import fs from 'fs';
import path from 'path';
export default function dataHander(dataDir) {
return function(req, res) {
fs.readdir(dataDir, (err, fileNames) => {
if (!err) {
res.set('Content-Type', 'application/json');
const dataFiles = fileNames.reduce((result, fileName) => {
const matchData = fileName.match(/^(.*?)\.json$/);
if (matchData) {
result.push({
fileName: path.join(dataDir, fileName),
key: matchData[1]
});
}
return result;
}, []);
let filesSent = 0;
res.write('{');
dataFiles.forEach(({fileName, key}) => {
fs.readFile(fileName, (err, fileContent) => {
if (!err) {
if (filesSent) res.write(',');
res.write(JSON.stringify(key) + ':' + fileContent);
}
filesSent++;
if (filesSent === dataFiles.length) {
res.write('}');
res.end();
}
});
});
} else {
res.status(500).send('Failed to read data directory');
}
});
};
}