-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path3-http.js
More file actions
35 lines (29 loc) · 799 Bytes
/
3-http.js
File metadata and controls
35 lines (29 loc) · 799 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
'use strict';
const threads = require('node:worker_threads');
const http = require('node:http');
const port = 8000;
threads.parentPort.postMessage({ name: 'started', port });
const routing = {
'/': async (req, res) => ({ status: res.statusCode }),
'/api/method': async (req, res) => ({ status: res.statusCode }),
};
const types = {
object: JSON.stringify,
string: (s) => s,
number: (n) => n.toString(),
undefined: () => 'not found',
};
http
.createServer(async (req, res) => {
const handler = routing[req.url];
if (!handler) {
res.end('Handler not found');
return;
}
const data = await handler(req, res);
const type = typeof data;
const serializer = types[type];
const result = serializer(data);
res.end(result);
})
.listen(port);