The Node.js Execution Model
Many servers, such as Apache, maintain a pool of threads for handling multiple concurrent connections. As new connections are established, individual threads are delegated to handle them. Once the request has been serviced, the thread is returned to the pool for reuse by future requests. The problem with this approach is that it lacks scalability. For example, many web applications make AJAX connections which are kept alive indefinitely, consuming the available threads.
Node.js takes a completely different approach to servicing requests. The Node.js execution model is event-driven, and emphasizes asynchronous programming in order to maximize scalability. Node.js also utilizes non-blocking I/O to help conceal its biggest weakness ― the fact that it is single-threaded. Developers must constantly be aware of this limitation, as a single blocking I/O call can potentially grind the entire server to a halt. In the Node.js environment, many functions utilize callback functions which are executed upon completion of I/O events. Some developers find this style of coding to be awkward at first, however it is really no different from handling events on web pages.
Getting Started with Node.js
Node.js is free to use, and can be downloaded from the project’s home page. Binaries and source code are available for Windows, Mac, Linux, and SunOS. Once you have downloaded and installed the framework, you can begin developing Node.js applications.
The simplest “Hello World” Node.js program is shown below. The example uses the built-in
console object to display a message in a terminal window. Copy the following code into a new file named “hello.js”.
To run the example, type the following command in a terminal window.
If Node.js is configured properly, “Hello World!” will be displayed in the terminal window. Obviously, this is just barely scratching the surface of what Node.js can do. In the coming weeks, we will be diving deeper into the world of Node.js, so be sure to check back!