forked from darkreader/darkreader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
101 lines (86 loc) · 2.42 KB
/
Copy pathserver.js
File metadata and controls
101 lines (86 loc) · 2.42 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
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
94
95
96
97
98
99
100
101
// @ts-check
const http = require('http');
const path = require('path');
const url = require('url');
const mimeTypes = new Map(
Object.entries({
'.css': 'text/css',
'.html': 'text/html',
'.jpg': 'image/jpeg',
'.js': 'text/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.svg': 'image/svg+xml',
}),
);
async function createTestServer(/** @type {number} */port) {
/** @type {import('http').Server} */
let server;
/** @type {{[path: string]: string | import('http').RequestListener}} */
const paths = {};
/** @type {import('http').RequestListener} */
function handleRequest(req, res) {
const parsedURL = url.parse(req.url);
const pathName = parsedURL.pathname;
if (!paths.hasOwnProperty(pathName)) {
res.statusCode = 404;
res.end('Not found');
return;
}
const contentOrListener = paths[pathName];
if (typeof contentOrListener === 'function') {
const listener = contentOrListener;
return listener(req, res);
}
const content = contentOrListener;
const ext = pathName === '/' ? '.html' : path.extname(pathName);
const contentType = mimeTypes.get(ext) || 'text/plain';
res.statusCode = 200;
res.setHeader('Content-Type', contentType);
res.end(content, 'utf8');
}
/**
* @returns {Promise<void>}
*/
function start() {
return new Promise((resolve) => {
server = http
.createServer(handleRequest)
.listen(port, () => resolve());
});
}
/**
* @param {{[path: string]: string | import('http').RequestListener}} newPaths
*/
function setPaths(newPaths) {
Object.assign(paths, newPaths);
}
/**
* @returns {Promise<void>}
*/
function close() {
if (!server) {
return;
}
return new Promise((resolve) => {
server.close((err) => {
if (err) {
console.error(err);
}
server = null;
resolve();
});
});
}
process.on('exit', close);
process.on('SIGINT', close);
await start();
return {
setPaths,
close,
url: `http://localhost:${port}`,
};
}
module.exports = {
createTestServer,
};