Illustration of Yeti character writing with a pencil.

Do something cool with Node.js

Profile picture for user AlexH
Alex Hripak
Senior Developer

I’ve been watching a new competition for the past couple weeks called Moduleoff. It’s a bi-weekly Drupal module development challenge. You are given a set of criteria and then you are required to submit a video and sample module. (You even receive a prize if you win!)

At last, a challenge I had an idea for—Challenge 5: Do something cool with Node.js

I ended up going with a module that somewhat mimics the functionality of Real time Google Analytics. It only makes sense to use Node.js to provide a real time dashboard; that shows the user all the requests coming in and some ancillary data about them, like location and username. Plus, with Drupal, we have many contributed modules ready for use; I ended up using Hostip for determining location and Visualization API for rendering the charts.

Sweet Code

Other than leveraging the contributed modules, the real guts and real time data is going to be handled by Node.js and the integration module for Drupal.

The integration module is message based; when you want something to occur, you send a message. We can send messages to users in a channel pretty easily. Here I am sending some arbitrary data to the nodejsaccesslog channel and specifying the nodejsaccesslog callback.

$message = (object) array(
  'channel' => 'nodejs_accesslog',
  'data' => array(
    'access' => l($current_path, $current_path, array('attributes' => array('target' => '_blank'))),
    'period' => _nodejs_accesslog_get_period(),
    'user' => format_username($user),
    'country' => _nodejs_acceslog_get_country(),
  ),
  'callback' => 'nodejs_accesslog',
);
nodejs_send_message($message);

Important to note that you should almost always use a channel, because if you end up with multiple uses for Node.js on your site you could run into conflicts—and even worse, having the wrong users receive data.

Then on the client side, the callbacks will get called with the message we just sent. At this point you can do whatever you desire with the message data. In our case we refresh the charts and table, but below you see a limited version of the real file.

Drupal.Nodejs.callbacks.nodejs_accesslog = {
  callback: function(message) {
    \\\\ Switch on channel and ignore messages that might have broadcast => TRUE
    switch(message.channel) {
    case 'nodejs_accesslog':
      \\\\ do stuff with message.data (the same data array that we made when we did nodejs_send_message() in PHP
      break;
    }
  }
};

Goodies

There’s a demo running on my personal Linode here: nodejs_accesslog.alexdoesit.com

The code is available on my Github here: github.com/alexh58/nodejs_accesslog

And as stated in the submission guidelines, below is a video with a brief explanation and demo of the module.

More Resources

comments powered by Disqus