-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
68 lines (53 loc) · 1.93 KB
/
Copy pathindex.js
File metadata and controls
68 lines (53 loc) · 1.93 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
68
const bodyParser = require('body-parser');
const cors = require('cors');
const express = require('express');
const fs = require('fs');
const morgan = require('morgan');
const path = require('path');
const util = require('util');
const PORT = 8081;
const readDirAsync = util.promisify(fs.readdir);
const setTimeoutAsync = util.promisify(setTimeout);
async function getFilenamesAsync(dirPath) {
const dirents = await readDirAsync(dirPath, { withFileTypes: true });
let filePaths = dirents.filter(d => d.isFile()).map(d => path.join(dirPath, d.name));
const directories = dirents.filter(d => d.isDirectory());
const promises = directories.map((d) => getFilenamesAsync(path.join(dirPath, d.name)));
const results = await Promise.all(promises);
results.forEach((arr) => {
filePaths = filePaths.concat(arr);
});
return filePaths;
}
async function getAllFilenamesAsync() {
const basePath = path.join(__dirname, '/node_modules');
const files = await getFilenamesAsync(basePath);
return files.map(f => path.relative(basePath, f));
}
async function main() {
const app = express();
const logger = morgan('dev');
const files = await getAllFilenamesAsync();
files.sort();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.use(logger);
app.use('/static', express.static('node_modules'));
app.get('/search', async function(req, res) {
const randomDelay = !!JSON.parse(req.query.randomDelay || 'false');
const prefix = req.query.prefix || '';
const count = parseInt(req.query.count, 10) || 10;
const results = files.filter(f => f.startsWith(prefix));
if (randomDelay) {
await setTimeoutAsync(Math.random() * 3000);
}
res.send({ results: results.slice(0, count) });
});
app.use('/', function(req, res) {
res.sendFile(path.join(__dirname, '/index.html'));
});
console.log('Server started on port', PORT);
app.listen(PORT);
}
main();