8. Blocking I/O Synchronous I/O Wait for I/O operations to complete Idle time var post = db.query(“select * from posts where id = 1”); // waiting, waiting, waiting showPost(post); // do something unrelated to post doAnotherThing();
9. Non-Blocking I/O Asynchronous I/O Continue processing Improve throughputand latency var post = db.query(“select * from posts where id = 1”, callback); doAnotherThing(); callback = function(post){ showPost(post); }
16. A simple web server var http = require("http"); http.createServer(function(req, res){ res.writeHead(200, {"Content-Type": "text/plain"}); return res.end("Hello Barcamp Saigon"); }).listen(8080); console.log("Server running at port 8080");
17. Callback var http = require("http"); var callback = function(req, res){ res.writeHead(200, {"Content-Type": "text/plain"}); return res.end("Hello Barcamp Saigon"); } http.createServer(callback).listen(8080); console.log("Server running at port 8080");
18. Event binding var fs = require(“fs"); var readStream = fs.createReadStream(“/etc/sources”); readStream.addListener(“data”, function(data){ console.log(data); }); readStream.addListener(“end”, function(data){ console.log(“file ended”); });
19. Parallel vs. Serial var fs = require("fs"); function writeBarcamp(){ return fs.writeFile('./barcamp.txt', 'Hi Barcamp!', function writeFile(err){ fs.readFile('./barcamp.txt', 'UTF-8', readFile); }); } function writeNode(){ return fs.writeFile('./node.txt', 'Hi Node!', function writeFile(err){ fs.readFile('./node.txt', 'UTF-8', readFile); }); } function readFile(err){} writeBarcamp(); writeNode();