Node.js is a great tool in some circumstances. In this post I discuss what Node.js is, and why I like it. If you’ve ever wondered what it is, but never had the time to read up on it, this 5 minute read is for you…
I’m writing this post because like many people I’d heard of Node.js but never had the time, or a good work reason, to get familiar with it. Toward the end of last year I did though, so I thought I’d share my reasons for using it, and why I fell in love with Node.js.
Sounds complicated, but actually it’s not. All you’re doing is saying ‘set me up a listener on port 80. When you receive a http request on there, fire this event handler’. You’re basically setting up the minimum you need, then intercepting application level events.
That’s the other thing about Node.js – it’s entirely event driven and non blocking. This means there is no function saying ‘wait for keyboard input before proceeding in my programme’. Instead you say ‘go off and do this, and when something happens, here’s the handler to use’. For everything.
What can you do with it?
Anything you like. I’ve used Node.js for a couple of demonstrations. Firstly, MarkLogic alerts occur very fast after a document has been added. To demo this you want something to happen immediately rather than after a few seconds of a polling web page to show it.
I’ve used Node.js to act as a http server to receive MarkLogic alerts and then do something immediate to show the results. (I.e. tell a user about a new ‘document’). In one scenario this meant sending an Instant Message via a local Jabber server. This makes a nice point of desktop integration with a database. I also added functionality there to interpret what messages a user sent to the Jabber server, and create a MarkLogic search from them and return a list of results.
The other use is as a WebSockets server. MarkLogic server supports a variety of server modules, one of which is http. Unfortunately, currently that doesn’t support the WebSockets API. This is one of many API under the ‘HTML 5’ banner. You use this to keep a connection open between a browser application and a server instead of polling the server every few seconds to see if something has happened.
I’ve created a web application that uses WebSockets for this purpose, and used Node.js to create a http server to receive events from MarkLogic, and fire them down a WebSockets pipe to the application client. In the HTML 5 app I then displayed these results visually. They were map tiles and asset location information. You saw them move and update in real time. I used MLCP to fire bunches of data to MarkLogic so you could watch the display change as new information hit the database and was alerted to the client application.
I effectively use it as glue for technology that isn’t built in to MarkLogic server. It works very well for this. Indeed, you can write a couple of hundred lines of code for your integration project rather than thousands in Java using heavyweight server technology.