Node.js

& Drupal

Created by Alex Hripak / @alexh58

:/ root$ WHOAMI;

What is Node.js?

  • Server side JavaScript
  • Based on Chrome's V8 JavaScript engine
  • Event Driven
  • Asynchronous in nature

Apache Pitfalls

  • Memory heavy
  • One thread per connection
  • Persistent connections are bad

Node.js is single process and multi-threaded. Great for integrating other services.

Limiting Factors

With Apache...

  • memory_limit
  • max_execution_time
  • MaxClients

With Node.js...

  • How many open sockets can you have?
  • How much bandwidth can you grab?
  • How fast can you issue requests?

A Good Use Case

Hypothetical Mail With PHP

$count = 0;
$emails = array(
  'alex@example.com',
  'rob@example.com',
  'tom@example.com',
);

foreach($emails as $email) {
  if(drupal_mail($module, $key, $email, language_default(), array(), 'alex@left-click.us', TRUE)) {
    $count++;
  }
}

echo "We sent {$count} email(s).";

Hypothetical Mail With Node.js

var mail = require('mail');
var emails = [
  'alex@example.com',
  'rob@example.com',
  'tom@example.com'
];

emails.forEach(function(email, i) {
  mail(email, $message, 'alex@left-click.us', function(error) {
    if(!error) { count++; }
    if(i == emails.length - 1) {
      console.log("We sent " + count + " email(s).");
    }
  });
});

console.log("We've finished the script.");

Yea yea yea...


Make it work with Drupal Plz!

Node.js Module

  • http://drupal.org/project/nodejs
  • Made by Justin Randell AKA beejeebus
  • Provides server.js and a Drupal module
  • It's an API so you can implement node in your own way

How to Implement

Server side: Send Event

$message = (object) array(
  'channel' => 'mymodule',
  'data' => array(
    'mymessage' => 'The Actual Message',
  ),
);

nodejs_enqueue_message($message);

Client side: Receive Event

Drupal.Nodejs.callbacks.mymodule = {
  callback: function(message) {
    if(message.channel == 'mymodule') {
      console.log(message.data.mymessage);
    }
  }
};

Hooks

  • hook_nodejs_handlers_info()
  • hook_nodejs_user_channels()
  • hook_nodejs_auth_check()

Helper Functions

  • nodejs_add_user_to_channel()
  • nodejs_remove_user_from_channel()
  • nodejs_kick_user()
  • nodejs_broadcast_message()


You can also
drush broadcast-message "Hello" "World"

Demo

QA & Resources



Slides and demo available at

http://goo.gl/DtjoR