forked from HowProgrammingWorks/Threads
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3-http.js
More file actions
33 lines (27 loc) · 757 Bytes
/
3-http.js
File metadata and controls
33 lines (27 loc) · 757 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
'use strict';
const threads = require('worker_threads');
const http = require('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);