Node.js ノンブロッキング処理

Node.jsのノンブロッキング処理を見てみましょう。下記のように、コールバック関数を実装すれば、次の処理をブロックしませんの、”world”を先にwriteします。

hello.js

setTimeout(function(){
  console.log("hello");
}, 1000);
console.log("world");
[vagrant@localhost nodejs]$ node hello.js
world
hello

コールバックの仕組みですね。
/*
Node is all about non-blocking, asynchronous architecture. This means any activity taking a long time to finish, such as file access, network communication, and database operations, are requested and put aside until the results are ready and returned via a callback function. Instead of asking to read a file and waiting for the operating system to come back with a file handler or buffer, the a callback function is invoked when the operation is completed, freeing the server to handle additional requests.
*/