8000 Start http server from worker · HowProgrammingWorks/Threads@6051384 · GitHub
[go: up one dir, main page]

Skip to content

Commit 6051384

Browse files
committed
Start http server from worker
1 parent 985f050 commit 6051384

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

JavaScript/3-http.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
'use strict';
2+
3+
const threads = require('worker_threads');
4+
const http = require('http');
5+
6+
const port = 8000;
7+
8+
threads.parentPort.postMessage({ name: 'started', port });
9+
10+
const routing = {
11+
'/': async (req, res) => {
12+
return { status: res.statusCode };
13+
},
14+
'/api/method': async (req, res) => {
15+
return { status: res.statusCode };
16+
},
17+
};
18+
19+
const types = {
20+
object: JSON.stringify,
21+
string: s => s,
22+
number: n => n.toString(),
23+
undefined: () => 'not found',
24+
};
25+
26+
http.createServer(async (req, res) => {
27+
const handler = routing[req.url];
28+
if (!handler) {
29+
res.end('Handler not found');
30+
return;
31+
}
32+
const data = await handler(req, res);
33+
const type = typeof data;
34+
const serializer = types[type];
35+
const result = serializer(data);
36+
res.end(result);
37+
}).listen(port);

JavaScript/3-server.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
'use strict';
2+
3+
const threads = require('worker_threads');
4+
const { Worker } = threads;
5+
6+
const worker = new Worker('./3-http.js');
7+
8+
worker.on('message', msg => {
9+
if (msg.name === 'started') {
10+
console.log(`HTTP Server Started on ${msg.port}`);
11+
}
12+
});
13+
14+
process.on('SIGTERM', () => {
15+
worker.terminate(() => {
16+
console.log('HTTP Server Stopped');
17+
});
18+
});

0 commit comments

Comments
 (0)
0