epoll
kqueue
event ports
Thread Pool
linux
BSD
SunOS
IOCP
Windows
Network I/O
File I/O
DNS
...
Non-Blocking I/O
Blocking I/O
UV_THREADPOOL_SIZE=8 (SIZE<=128)
Thread pool
Blocking I/O
CPU intensive
NOW: Up to 1024 threads (after libuv v1.30.0 or node v12.5.0)
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isPrimary) {
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
// ...
} else {
// Workers can share any TCP connection
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
}
// Main process -> script.js
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js');
worker.on('message', (msg) => {
console.log('Message', msg);
});
worker.on('error', console.error);
worker.on('exit', (code) => {
console.log('Exit', code);
});
// Thread -> worker.js
const { parentPort } = require("worker_threads");
parentPort.postMessage('Greetings from thread!');
$ node script.js
Message Greetings from thread!
Exit 0