Monday, May 23, 2011
Sometime last year I came across Node.js, the server-side port of Google’s V8 ECMAScript engine. At first I was interested in it mostly as a novelty to allow things like form validation library portability from client to server side. After trying it out and reading through the documentation in more detail and watching Ryan’s presentation, I became a lot more excited about it.
Since Node.js is essentially just a set of bindings for V8 to allow it to interact with a server type environment instead of the more familiar DOM, Ryan had complete freedom to implement all of the core I/O API calls in a way that relies exclusively on callbacks to avoid blocking. It is this clever trick that allows Node.js to perform extremely well in unexpected roles such as webserver, while at the same time avoiding the complex select event loop logistics usually associated with single-threaded daemons. This also sidesteps the entire can of thread-synchronization worms usually associated with high-performance network service.
To show how this works, here is a naive script which implements a memcached-like network memory cache in just a handful of lines of code:
Here is what it looks like when you telnet to it:
And this is what the server log looks like:
Of course, there are many more things you can do with prototype style inheritance, but this demonstrates that it can be used to emulate the classical class mechanism and also demonstrates the use of a closure to bind the local “host” variable to the callback provided to the lineParser constructor.