The face of web development today is dramatically different !
The things that we can do on the web nowadays with JavaScript running on the server, as well as in the browser, were hard to imagine just several years ago.
This technology, called Node.js, is being hailed as “the new Ruby on Rails” by some in the developer community.
It’s not a magic bullet, nor is it appropriate for all programming scenarios. But, the common wisdom among many developers is that there is no single right language that must be used for all web apps. But Node is increasingly being seen as a “best solution” for a certain type of application.
Before starting using Node.js, I feel we must first understand the differences between Node.js and traditional server-side scripting environments (eg: PHP, Python, Ruby, etc)
1. Set of libraries written on top of very powerful VM called V8
Node.js is a packaged compilation of Google’s V8 JavaScript engine, the libuv platform abstraction layer, and a core library, which is itself primarily written in JavaScript.” Beyond that, it’s worth noting that Ryan Dahl, the creator of Node.js, was aiming to create real-time websites with push capability. In Node.js, he gave developers a tool for working in the non-blocking, event-driven I/O paradigm
2. HTTP 1.1
Node.js shines in real-time web applications employing push technology over websockets. What is so revolutionary about that? Well, after over 20 years of stateless-web based on the stateless request-response paradigm, we finally have web applications with real-time, two-way connections, where both the client and server can initiate communication, allowing them to exchange data freely. This is in stark contrast to the typical web response paradigm, where the client always initiates communication. Additionally, it’s all based on the open web stack (HTML, CSS and JS) running over the standard port 80.
One might argue that we’ve had this for years in the form of Flash and Java Applets—but in reality, those were just sandboxed environments using the web as a transport protocol to be delivered to the client. Plus, they were run in isolation and often operated over non-standard ports, which may have required extra permissions and such.
3. Event-driven asynchronous callbacks
To understand why Node.js applications have to be written this way, we need to understand how Node.js executes our code. Node’s approach isn’t unique, but the underlying execution model is different from runtime environments like Python, Ruby, PHP or Java.
Let’s take a very simple piece of code like this:
var result = database.query(“SELECT * FROM hugetable”); console.log(“Hello World”); The first line queries a database for lots of rows, the second line puts “Hello World” to the console.
Let’s assume that the database query is really slow.
The way we have written this code, the JavaScript interpreter of Node.js first has to read the complete result set from the database, and then it can execute the console.log() function.
If this piece of code actually was, say, PHP, it would work the same way: read all the results at once, then execute the next line of code. If this code would be part of a web page script, the user would have to wait several seconds for the page to load.
However, in the execution model of PHP, this would not become a “global” problem: the web server starts its own PHP process for every HTTP request it receives. If one of these requests results in the execution of a slow piece of code, it results in a slow page load for this particular user, but other users requesting other pages would not be affected.
The execution model of Node.js is different – there is only one single process. If there is a slow database query somewhere in this process, this affects the whole process – everything comes to a halt until the slow query has finished.
To avoid this, JavaScript, and therefore Node.js, introduces the concept of event-driven, asynchronous callbacks, by utilizing an event loop.
database.query(“SELECT * FROM hugetable”, function(rows) { var result = rows; }); console.log(“Hello World”);
Now, Node.js can handle the database request asynchronously. Provided that database.query() is part of an asynchronous library, this is what Node.js does: just as before, it takes the query and sends it to the database. But instead of waiting for it to be finished, it makes a mental note that says “When at some point in the future the database server is done and sends the result of the query, then I have to execute the anonymous function that was passed to database.query().”
Then, it immediately executes console.log(), and afterwards, it enters the event loop. Node.js continuously cycles through this loop again and again whenever there is nothing else to do, waiting for events. Events like, e.g., a slow database query finally delivering its results.
http://www.sebastianseilund.com/nodejs-async-in-practice
4. Handles concurrency very well than our traditional web server
Node.js is only an environment – meaning that you have to do everything yourself. There is not a default HTTP server, or any server for that matter. This can be overwhelming for new users, but the payoff is a high performing web app. One script handles all communication with the clients. This considerably reduces the number of resources used by the application. For example, here is the code for a simple Node.js application:
var i, a, b, c, max; max = 1000000000; var d = Date.now(); for (i = 0; i < max; i++) { a = 1234 + 5678 + i; b = 1234 * 5678 + i; c = 1234 / 2 + i; } console.log(Date.now() – d);
And here is the equivalent written in PHP:
$a = null; $b = null; $c = null; $i = null; $max = 1000000000; $start = microtime(true); for ($i = 0; $i < $max; $i++) { $a = 1234 + 5678 + $i; $b = 1234 * 5678 + $i; $c = 1234 / 2 + $i; } var_dump(microtime(true) – $start);
Now let’s look at the benchmark numbers. The following table lists the response times, in milliseconds, for these two simple applications. PHP is notably faster with a smaller amount of iterations, but that advantage quickly dissolves as the number of iterations increases. When all is said and done, PHP is 93% slower than Node.js!
Have a look at Node vs Apache PHP benchmark test
5. NPM: The Node Package Manager
The idea of NPM modules is quite similar to that of Ruby Gems: a set of publicly available, reusable components, available through easy installation via an online repository, with version and dependency management.
A full list of packaged modules can be found on the NPM website https://npmjs.org/ , or accessed using the NPM CLI tool that automatically gets installed with Node.js. The module ecosystem is open to all, and anyone can publish their own module that will be listed in the NPM repository. A brief introduction to NPM (a bit old, but still valid) can be found at http://howtonode.org/introduction-to-npm.
Some of the most popular NPM modules today are:
- express – Express.js, a Sinatra-inspired web development framework for Node.js, and the de-facto standard for the majority of Node.js benefits out there today.
- connect – Connect is an extensible HTTP server framework for Node.js, providing a collection of high performance “plugins” known as middleware; serves as a base foundation for Express.
- socket.io and sockjs – Server-side component of the two most common websockets components out there today.
- Jade – One of the popular templating engines, inspired by HAML, a default in Express.js.
- mongo and mongojs – MongoDB wrappers to provide the API for MongoDB object databases in Node.js.
- redis – Redis client library.
- coffee-script – CoffeeScript compiler that allows developers to write their Node.js programs using Coffee.
- underscore (lodash, lazy) – The most popular utility library in JavaScript, packaged to be used with Node.js, as well as its two counterparts, which promise better performance by taking a slightly different implementation approach.
- forever – Probably the most common utility for ensuring that a given node script runs continuously. Keeps your Node.js process up in production in the face of any unexpected failures.
Node.js requires extra work, but the payoff of a fast and robust application is worth it. If you don’t want to do everything on the lowest level, you can always pick some framework, such as Express, to make it easier to develop applications.
Node.js is a promising technology and an excellent choice for a high load application. It has been proven by corporations, like Microsoft, eBay, and Yahoo. If you’re unsure about hosting your website/application, you can always use a cheap VPS solution or various cloud-based services, such as Microsoft Azure and Amazon EC2. Both of these services provide scalable environments at a reasonable price.
References: