-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path3-server.js
More file actions
43 lines (35 loc) · 824 Bytes
/
3-server.js
File metadata and controls
43 lines (35 loc) · 824 Bytes
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
'use strict';
const fs = require('node:fs');
const http = require('node:http');
const cache = new Map();
const cacheFile = (path) => {
fs.readFile(path, 'utf8', (err, data) => {
if (err) {
cache.delete(path);
return;
}
cache.set(path, data);
});
};
const cacheFolder = (path) => {
fs.readdir(path, (err, files) => {
if (err) return;
files.forEach(cacheFile);
});
};
const watch = (path) => {
fs.watch(path, (event, file) => {
cacheFile(file);
});
};
const path = './';
cacheFolder(path);
watch(path);
http.createServer((req, res) => {
const url = req.url.substring(1);
console.log(url);
const data = cache.get(url);
if (data) res.end(data);
else res.end('File ' + url + 'not found');
}).listen(8000);
// See https://github.com/HowProgrammingWorks/LiveReload