I'm learning node.js from the Node Beginner Book and the subsequent ebook purchase. In the book, Manuel Kiessling explains that a line of blocking code like this one:
fs.readFileSync(blah);
will block the entire node process and ALL requests coming in. This is really bad for a multi-user website!
This is the example, Kiessling uses:
exec("ls -lah", function( error, stdout, stderr ) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(stdout);
response.end();
});
This is the code that tricked me. He says the ls -lah
could easily be replaced with a more time consuming operation like find / -name "*"
or a database lookup. I assumed the expensive and blocking operation would somehow run in the background explicitly because of the async callback.
So I got to testing my theory with this code:
var http = require("http");
var url = require("url");
badSleep = function(ms) {
var now = new Date();
var finishAtDate = now.getTime() + ms;
console.log("CPU burning sleep for " + ms + " milliseconds");
while(new Date() < finishAtDate) {
// do nothing
}
};
asyncWrapper = function(callback) {
//badSleep(3000);
callback();
}
http.createServer(function(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Serve up " + pathname);
if (pathname == '/favicon.ico') {
response.writeHead(404);
response.end();
} else {
asyncWrapper(function() {
badSleep(3000);
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("\nI was wrong " + new Date());
response.end();
});
}
}).listen(8888);
The thing is, no matter where I put the sleep, it still blocks the node event loop. The callback does not solve the blocking problem. The good users of SO told me this also in the comments.
So how does exec
do it??? I was baffled, so I went and looked at the child-process code at github. I found out that exec
calls spawn
!!! It makes a child process! Mystery solved. The async code does not 'solve' the blocking issue, the spawn does.
That leads me to my question. Does express somehow solve the blocking problem or do you still have to worry about it?