In the excellent book Node.js the right way the author shows this example:
const
fs = require('fs'),
zmq = require('zmq'),
// socket to reply to client requests
responder = zmq.socket('rep');
// handle incoming requests
responder.on('message', function(data) {
// parse incoming message
let request = JSON.parse(data);
console.log('Received request to get: ' + request.path);
// read file and reply with content
fs.readFile(request.path, function(err, content) {
console.log('Sending response content');
responder.send(JSON.stringify({
content: content.toString(),
timestamp: Date.now(),
pid: process.pid
}));
});
});
and then says:
There is a catch to using ØMQ REP/REQ socket pairs with Node. Each endpoint of the application operates on only one request or one response at a time. There is no parallelism.
He then uses the nodejs cluster module to fix that scaling issue.
I was surprised by that the, whole concept of nodejs
and the book is nio
and asyncrhonisity
so I was more like expecting this solution:
- Request arrives and handled by zmq.
fs
handles it asynchronously.- More requests arrive and handled by zmq.
- All are directed to
fs
asynchronousreadFile
nio. - Once there is a callback from
fs.readFile
zmqresponder
is initiated for each nio which completes.
in this way with a single event loop and single thread for the requests to zmq we can serve multiple requests. Why isn't that the case? Must we open more threads to increase scale? Why can't nio
and asynchronousity help with our single thread?