File tree Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change
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 ) ;
Original file line number Diff line number Diff line change
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
+ } ) ;
You can’t perform that action at this time.
0 commit comments