VS Epxress The key difference between Koa and Express is how they handle middleware. Express includes routing and templates in the application framework. Koa, on the other hand, requires modules for these features, therefore making it more modular or customizable.
const http = require('http'); const numCPUs = require('os').cpus().length; const cluster = require('cluster'); if(cluster.isMaster){ console.log(`Master process id is ${process.pid}, cpu number ${numCPUs}`); // fork workers for(let i= 0;i<numCPUs;i++){ cluster.fork(); } cluster.on('exit',function(worker,code,signal){ console.log('worker process died,id',worker.process.pid) }) }else{ // Worker can share the same TCP connection // It's an http server here console.log(`created worker pid ${process.pid}`) http.createServer(function(req,res){ res.writeHead(200); res.end(String(process.pid)); }).listen(8000);
}
Running code above, we got:
1 2 3 4 5
Master process id is 18428, cpu number 4 created slave pid 16672 created slave pid 9896 created slave pid 14676 created slave pid 1460
We can find these process in task manager:
Now send a request in browser, and id of one of the four server process is returned:
Try refresh many times and different pids may return(It depends, maybe one unlucky process shoulders all the workload). Now kill one the worker 1460 in task manger and we got:
1
worker process died,id 1460
Refresh the browser and result is another pid other than 1460:
You see, now our server is much more robust than before. We got four worker process, killing one of them and there are still three working.
Cluster calls the same fork method from child_process module under the hood. Cluster is a master-slave model, where master manages and schedules slaves.
Why no Error: EADDRINUSE when multiple processes listens on the same port? The child processes aren’t listening to the same port. Incoming socket connections to the master process are being delegated to the child processes. There’s special handling for clustered process in server.listen(), it calls a method named listenInCluster() in some circumstances. See explanation here
Multithreading vs multiprocess
cluster
One process is launched on each CPU and can communicate via IPC.
Each process has its own memory with its own Node (v8) instance. Creating tons of them may create memory issues.
Great for spawning many HTTP servers that share the same port b/c the master process will multiplex the requests to the child processes.
worker threads
One process total
Creates multiple threads with each thread having one Node instance (one event loop, one JS engine). Most Node API’s are available to each thread except a few. So essentially Node is embedding itself and creating a new thread.
Shares memory with other threads (e.g. SharedArrayBuffer)
Great for CPU intensive tasks like processing data or accessing the file system. Because NodeJS is single threaded, synchronous tasks can be made more efficient with workers