forked from willnode/forward-domain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstat.js
69 lines (63 loc) · 2.03 KB
/
stat.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
import { config } from "dotenv";
import { execSync } from "child_process";
import http from "http";
import { isMainProcess } from "./src/util.js";
const updateStat = function () {
// run npm stat
var buffer = execSync('npm run count');
var lines = buffer.toString('utf-8').trimEnd().split('\n');
var stat = {
domains: parseInt(lines[lines.length - 1]),
iat: Date.now(),
exp: Date.now() + 1000 * 60 * 60 * 24,
};
return stat;
};
let cacheStat = updateStat();
const listener = async function (/** @type {import('http').IncomingMessage} */ req, /** @type {import('http').ServerResponse} */ res) {
try {
// handle CORS
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Max-Age', '86400');
if (req.method === 'OPTIONS') {
res.statusCode = 204;
return;
}
switch (req.url) {
case '/':
if (cacheStat.exp < Date.now()) {
cacheStat = updateStat();
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(cacheStat));
break;
default:
res.writeHead(404, {
'Content-Type': 'application/json'
});
res.write(JSON.stringify({
error: 'Unknown url'
}));
break;
}
return;
}
catch (error) {
res.writeHead(400);
res.write(error.message || 'Unknown error');
}
finally {
res.end();
}
};
const server = http.createServer(listener);
if (isMainProcess(import.meta.url)) {
config();
const port = parseInt(process.env.STAT_PORT || "3000");
server.listen(port, function () {
console.log(`server start at port ${port}`);
});
}
export default server;