Node.js Hosting Platform Modulus Goes Public Beta

After several months of invite only access, the Node.js hosting platform Modulus has opened its doors to everyone.

Modulus is a full-featured Node.js platform service that provides support for WebSockets, custom domains, custom SSL, integrated MongoDB, and powerful statistics and metrics.

Registration and application hosting are completely free during the public beta, so this is the perfect time to jump on and test drive this new product.

Node.js and Express – Basic Authentication

Basic authentication can be a quick and efficient way to protect your content. Combined with SSL it’s also very secure. This article describes how to add basic authentication to a Node.js Express application.

Express App

The first thing we need is an Express application. Creating an Express app is extremely simple, and the makers of Express do a pretty good job documenting the process.

package.json

{
  "name" : "BasicAuthExample",
  "version" : "0.0.1",
  "dependencies" : {
    "express" : "3.x"
  }
}

app.js

var express = require(‘express’);
var app = express();

app.get(‘/home’, function(req, res) {
 res.send(‘Hello World’);
});

app.listen(process.env.PORT || 8080);

The application has one route defined, /home. Right now there is no authentication. Anyone can access /home and see the content. If you host the application on Modulus the PORT environment variable will be defined, otherwise I’m simply using 8080.

Global Authentication

The first technique we’ll see is adding authentication globally to every route. Fortunately with Express, we can do this with a single line.

Synchronous

This technique is the simplest, but least flexible. The authentication will occur synchronously with hard-coded values.

var express = require(‘express’);
var app = express();

// Authenticator
app.use(express.basicAuth(‘testUser’, ‘testPass’));

app.get(‘/home’, function(req, res) {
 res.send(‘Hello World’);
});

app.listen(process.env.PORT || 8080);

In this example, to access any route in our application the user must enter the username, ‘testUser’, and the password, ‘testPass’.

Synchronous Function

The second technique is also synchronous, but provides a little more flexibility. This time we’re going to define a function that simply has to return true or false.

var express = require(‘express’);
var app = express();

// Authenticator
app.use(express.basicAuth(function(user, pass) {
 return user === ‘testUser’ && pass === ‘testPass’;
}));

app.get(‘/home’, function(req, res) {
 res.send(‘Hello World’);
});

app.listen(process.env.PORT || 8080);

As you can see, we now pass a function as the authentication mechanism instead of the username and password. The function gets as arguments the username and password specified by the user. Technically you don’t even need to use these as part of the authentication, since all you have to do is return true or false.

Asynchronous

The last technique is the most flexible. With an async callback you could lookup the username and password in a database.

var express = require(‘express’);
var app = express();

// Authenticator
app.use(express.basicAuth(function(user, pass, callback) {
 var result = (user === ‘testUser’ && pass === ‘testPass’);
 callback(null /* error */, result);
}));

app.get(‘/home’, function(req, res) {
 res.send(‘Hello World’);
});

app.listen(process.env.PORT || 8080);

This example also takes a function, but instead of only passing the username and password, it also passes a callback function that should be invoked with the result. The callback utilizes the error-first pattern, so the first parameter should be null if no errors occurred. The second parameter to the callback is the result (true or false) of the authentication.

Single-Route Authentication

The above three techniques can also be used to secure individual routes. Just like before we define our authentication handler, except this time we need to save it to a variable.

// Synchronous
var auth = express.basicAuth(‘testUser’, ‘testPass’);

// Synchronous Function
var auth = express.basicAuth(function(user, pass) {
 return user === ‘testUser’ && pass === ‘testPass’;
});

// Asynchronous
var auth = express.basicAuth(function(user, pass, callback) {
 var result = (user === ‘testUser’ && pass === ‘testPass’);
 callback(null /* error */, result);
});

All that we have to do now is pass the authenticator to the routes we’d like protected.

app.get(‘/home’, auth, function(req, res) {
 res.send(‘Hello World’);
});

app.get(‘/noAuth’, function(req, res) {
 res.send(‘Hello World – No Authentication’);
});

As you can see, the /home route still requires authentication since we’ve passed the authenticator as the second parameter. The /noAuth route is publically available since an authenticator was not supplied.

And there you have it. We’ve seen all the ways to add basic authentication to your Node.js Express application. If you’ve got any questions or comments leave them in the comments below.

This article is re-posted from the Modulus Blog with permission from the original authors.

Original source: Node.js and Express – Basic Authentication

Isaac Schlueter, Maintainer of Node.js, Answering Questions on Crowdhall

Isaac Schlueter, the author of NPM (npmjs.org) and the lead maintainer of Node.js is answering questions for the next few days on the open Q&A platform Crowdhall.

If you’ve got any questions about Node.js or Isaac’s personal life, now’s your change to ask him any question you’d like.

Simple Chat – Node.js + WebSockets

One of the best use cases for Node.js is real-time applications that handle lots of small requests simultaneously. A perfect example of this is a small chat application that allows multiple users to connect and send messages to each other. So today we are going to build this.

Simple Chat

Check out the live version.

We are going to be utilizing a technology called WebSockets, which will allow us to easily communicate between all of the users of our application. We are utilizing WebSockets via a Node module called Socket.IO. However, before we can dig into all the communications we are going to need some Node code.

For static content, we are using Express. May be a little overkill, but it does the job. The base app.js file will look like so:

var express = require(‘express’);
var app = express();
var server = require(‘http’).createServer(app);

server.listen(80);

app.use("/", express.static(__dirname + ‘/public’));

Nothing special. What we need now though is some Socket.IO action. We need to accept an incoming message then blast it out to everyone else that is listening to our server. Thankfully it is a small tweak on the server-side:

var express = require(‘express’);
var app = express();
var server = require(‘http’).createServer(app);
var io = require(‘socket.io’).listen(server);

server.listen(80);

app.use("/", express.static(__dirname + ‘/public’));

io.sockets.on(‘connection’, function (socket) {
  socket.on(‘msg’, function (data) {
    io.sockets.emit(‘new’, data);
  });
});

Yeap, a require statement and two callbacks later we have our server-side code. Basically what this is doing is waiting for a connection, then when a connection is established it subscribes to the “msg” event that happens when a client sends a message to the server. When this happens, we send the message to all connected clients, or “sockets” as they are called in this case. Simple stuff.

The client is a bit more complicated though. Let’s start with the HTML, which is pretty straight-forward.

<!DOCTYPE HTML>
<html>
  <head>
    <title>Simple Chat</title>
    <script type="text/javascript" src="/socket.io/socket.io.js"></script>
    <script
     type="text/javascript"
     src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
    </script>
  </head>
  <body>
    <div id="wrapper">
      <h1>Simple Chat</h1>
      <div id="messages"></div>
      <div class="nic">
        Your Name
        <input id="name" name="name" type="text"/>
      </div>
      <textarea id="message"></textarea>
      <input id="send" type="submit" value="Send"/>
    </div>
  </body>
</html>

The important bit here is the inclusion of /socket.io/socket.io.js. This is the client-side piece of socket.io, and will provide us with a simple way to communicate with our server. The coolest part is that the socket.io Node module sets up this route for us on the server, so we don’t have to do anything server-side to get this route to work.

To organize our chat code, we are going to create a JavaScript module which will provide a single, global instance to utilize. To start, let’s just get the module code:

//Create a chat module to use.
(function () {
  window.Chat = {
  };
}());

This will create a single instance of the Chat object in the global scope. However, we are going to need our Chat object to do something. Initialization is always pretty important, so we can add that next.

//Create a chat module to use.
(function () {
  window.Chat = {
    socket : null,
 
    initialize : function(socketURL) {
      this.socket = io.connect(socketURL);

      //Send message on button click or enter
      $(‘#send’).click(function() {
        Chat.send();
      });

      $(‘#message’).keyup(function(evt) {
        if ((evt.keyCode || evt.which) == 13) {
          Chat.send();
          return false;
        }
      });

      //Process any incoming messages
      this.socket.on(‘new’, this.add);
    }
  };
}());

In the initialize method, we are setting up the socket.io connection, subscribing to the new event, and making sure the send button and enter key do something productive. There is just one problem here, we don’t have an add function for the socket.on call to use. Let’s add that.

//Create a chat module to use.
(function () {
  window.Chat = {
    socket : null,
 
    initialize : function(socketURL) {
      this.socket = io.connect(socketURL);

      //Send message on button click or enter
      $(‘#send’).click(function() {
        Chat.send();
      });

      $(‘#message’).keyup(function(evt) {
        if ((evt.keyCode || evt.which) == 13) {
          Chat.send();
          return false;
        }
      });

      //Process any incoming messages
      this.socket.on(‘new’, this.add);
    },

    //Adds a new message to the chat.
    add : function(data) {
      var name = data.name || ‘anonymous’;
      var msg = $(‘<div class="msg"></div>’)
        .append(‘<span class="name">’ + name + ‘</span>: ‘)
        .append(‘<span class="text">’ + data.msg + ‘</span>’);

      $(‘#messages’)
        .append(msg)
        .animate({scrollTop: $(‘#messages’).prop(‘scrollHeight’)}, 0);
    }
  };
}());

Take some message data and add it to the DOM, that’s all we are doing here. Nothing special.

The final piece to this puzzle is actually sending the data.

//Create a chat module to use.
(function () {
  window.Chat = {
    socket : null,
 
    initialize : function(socketURL) {
      this.socket = io.connect(socketURL);

      //Send message on button click or enter
      $(‘#send’).click(function() {
        Chat.send();
      });

      $(‘#message’).keyup(function(evt) {
        if ((evt.keyCode || evt.which) == 13) {
          Chat.send();
          return false;
        }
      });

      //Process any incoming messages
      this.socket.on(‘new’, this.add);
    },

    //Adds a new message to the chat.
    add : function(data) {
      var name = data.name || ‘anonymous’;
      var msg = $(‘<div class="msg"></div>’)
        .append(‘<span class="name">’ + name + ‘</span>: ‘)
        .append(‘<span class="text">’ + data.msg + ‘</span>’);

      $(‘#messages’)
        .append(msg)
        .animate({scrollTop: $(‘#messages’).prop(‘scrollHeight’)}, 0);
    },

    //Sends a message to the server,
    //then clears it from the textarea
    send : function() {
      this.socket.emit(‘msg’, {
        name: $(‘#name’).val(),
        msg: $(‘#message’).val()
      });

      $(‘#message’).val();
    }
  };
}());

With socket.io you do two things: listen to events and trigger events. You listen with on (as we have seen), and you trigger events with the emit method. So when a message is ready to be sent, all we have to do is “emit” it with the message data. It will then be picked up on the server and emit it back out to all the sockets connected.

The only thing left to do is include it in the HTML and initialize it.

<!DOCTYPE HTML>
<html>
  <head>
    <title>Simple Chat</title>
    <script type="text/javascript" src="/socket.io/socket.io.js"></script>
    <script
     type="text/javascript"
     src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
    </script>
    <script type="text/javascript" src="chat.js"></script>
  </head>
  <body>
    <div id="wrapper">
      <h1>Simple Chat</h1>
      <div id="messages"></div>
      <div class="nic">
        Your Name
        <input id="name" name="name" type="text"/>
      </div>
      <textarea id="message"></textarea>
      <input id="send" type="submit" value="Send"/>
    </div>
    <script type="text/javascript">
      $(document).ready(function() {
        Chat.initialize(‘http://localhost/’);
      });
    </script>
  </body>
</html>

There it is, a complete chat application. If you run the Node script, it will start up and let you know socket.io is ready. Then you can bring up localhost and start chatting with…well, yourself if you run it locally. I have included all the code in a ZIP (or you can get it from github), as well as the addition of a little bit of “style” so it looks a little better. Don’t forget to npm install!

Hopefully this has been an informative, quick introduction to using WebSockets in Node.js. Just remember, when you need coding help, all you have to do is Switch On The Code.

A Simple jQuery Plugin Game

Today we are making a simple puzzle game called “Fifteen”. The purpose of the game is to slide 15 square blocks around to form an image. The goal of this tutorial is to look at this simple browser-based game and explain how it was made line by line. It’s a great way to learn jQuery!

For this tutorial, we will use a 2D image square-sliding game, which I will go over line by line to demonstrate the train of thought behind the code.

A jQuery plugin is a perfect way to create image slideshows, custom user interface controls and of course browser-based games. We won’t just write JavaScript code here, we will create a jQuery plugin.

A plugin is nothing more than our own custom jQuery method. You know how we have jQuery’s methods .css() and .animate()? Well, jQuery gives us the ability to extend its own functionality with custom methods that we create ourselves. Like the existing jQuery methods, we can apply the method we will create to a jQuery selector.

Well, the game is called Fifteen, and we want to make our game “embeddable” inside an arbitrary HTML element like <div id = "target">here</div> so we can move it around anywhere on the page (Different sites have different layouts, wouldn’t you like to have the ability to embed your jQuery game/plugin into an arbitrary DIV element on any site?)

Let’s get started with the jQuery code.

We will actually create our own jQuery method and call it .fifteen(). Therefore, in order to launch the game inside an HTML element with the id “target” we will call this command:

$("#target").fifteen(128);

This will create and attach the game board to the div whose id is “target.” Also, each square will become 128 by 128 pixels in width and height based on the only passed parameter.

Executing a custom method as shown in the code above will pass the selector string “#target” to our plugin function which grabs the DIV. Inside our custom method, we can refer to that selector/element using the this keyword. And we can also enable jQuery methods on it by passing it to the new jQuery object like so:

$(this);

In order to create our own jQuery plugin we will use the $.fn.extend() method.

We can also refer to this as extending functionality of the jQuery library with our own methods

Let’s take a look:

$.fn.extend({
  fifteen: function (square_size) {
    // Game code goes here…

    // Example — set the width of all\
    // DIVs to what was passed as square_size
    $("div").css({width: square_size});

    // The basics of the inner-workings of a plugin:
    // refers to the passed selector,
    // eg: $("#target")
    // same thing, but with jQuery methods enabled
    var a = this;                      
    var b = $(this);            

    // Let’s do something with the HTML
    // element passed as the CSS selector
    // paint all text inside "#target" red
    this.style.color = "red";
    // same exact thing, using jQuery method .css()  
    $(this).css("color", "red");
  }
});

That’s it! This is the basic structure of any jQuery plugin.

The code examples I use above are just examples that show how the basics work internally. But we will write an entire game within the scope of the function we called “fifteen”.

Within the scope of the plugin the this object refers to what was passed in the selector. Also, the square_size parameter is just a custom, arbitrary parameter passed to our game.

We decide what the parameters should be, and if your game or plugin require more, simply define more parameters, as in:

$.fn.extend({
  fifteen: function(square_size, param2, param3, etc) {
    /*.. game code…*/
  }
});

Within the scope of your plugin you refer to parameters by the very same names.

In our case square_size is the only parameter. It defines the arbitrary size of the square in the game. I use 128 (as in 128 pixels in width and height). The grid is 16 by 16, but there are only 15 movable squares, because one is always empty. However, we still create all 16 DIVs, and just make one white. We do this in order to simulate the shadow effect on an empty square.

Before we get into the code, let’s take a look at the game’s construction as far as HTML goes. You will notice that there are 16 squares and each square is a separate DIV element:

The Fifteen Game in Action

Well hello there…

You can see the game in action here.

The point of the game is to shuffle the image, one square at a time (by shifting it into the empty square, thus swapping locations) until the image is complete.

The white square is always empty. You are only allowed to shift squares that can physically be shifted into the empty spot, as if on a physical game board. This means only squares to the north, south, west and east of the empty square can be shifted. This test is performed within the stand-alone function I wrote and called Move() – it is separate from the plugin itself, it’s like a helper function.

Before we dive into the code, we need to briefly talk about some common problems we will face while designing a plugin-based game.

Embedding the Plugin Into Arbitrary DIVs (or other HTML elements)

Remember that when writing your plug-in it is wise to inject the HTML elements which are created as part of the game… into a parent DIV. The purpose of this is that your plug-in becomes embeddable into any arbitrary HTML element. Different websites have different layouts. So it’s important for our plug-in to be flexible. That it could be embedded into an arbitrary HTML element anywhere on the page. In this example I called that element:

<DIV id = "target"></DIV>

Moving around this element will physically move the game around anywhere on the page.

Injecting HTML into Empty Elements Using the .append(html) Method

We leave the div unpopulated, without any game HTML. Why’s that? This is because the plugin itself will generate the game’s HTML elements and insert them into the target DIV. No need to pre-type them “by hand.”

This is smart, because it keeps the parent element clean. But also, this example in particular allows us to explore the jQuery’s native .append(html) method. It literally appends new HTML at the end of a specified element. That is, you never even have to write HTML into the document itself, the .append() method injects HTML into the web page dynamically, you just specify the target element using a selector like:

// Add one div to the end of #board
$("#board").append("<div></div>");

Using :nth-child(index) Instead of IDs or Classes

I think it’s worth mentioning that we can refer to DIVs inside, say, a parent DIV as children. This is really helpful. For example, let’s say we have 16 DIVs (children) stored inside one parent DIV:

<div id = "board"> <!– This is called a "parent" element //–>
  <div></div>
  <div></div>
  <div></div>
  <!– … ok, imagine 16 DIVs here. These are the "children" of "#board" //–>
  <div></div>
  <div></div>
</div>

You don’t really need to assign 16 IDs to all 16 DIVs! jQuery takes care of that for us. For example, to refer to the 3rd DIV inside a parent DIV (in our game it’s #board,) instead, we can do something like this without ever assigning any classes or ids to any of the children:

// Hide 3rd DIV in the list of children.
//No need to assign an id to each one!
$("#board").children("div:nth-child(3)").hide();

Notice we used the .children() method to grab all children of a parent (DIVs inside parent,) and then we also specified that we need a 3rd child using the literal selector :nth-child(n) where n is the index of the DIV we need. Note, however that this index doesn’t start with 0 like JavaScript arrays. It starts with index of 1. :nth-child(0) will not select anything.

The Code

Well, I think we are ready to start writing the code. Let’s get to it.

// This is a JavaScript event.
// It means – once DOM is finished loading,
// execute everything inside the callback function scope
// This is where we initialize the game
$(document).ready(function()
{
  // Initialize the game and create the plugin

  // When the squares swap places, the moving square must always appear on top
  var zi = 1; // We increment z-index each time a square is shifted

  // The index of the empty square by default, the 16th square
  var EmptySquare = 16;

  // Now, this is where we create the plugin and call it fifteen.
  $.fn.extend({
    fifteen: function(square_size) {
      // Grab the id of the HTML element into which we are placing the game,
      // it is the selector – "#target" from  $("#target").fifteen(128);
      var targetElement = "#" + $(this).attr("id");

      var sqSize = square_size + ‘px’;
      var boardSize = (square_size * 4) + ‘px’;

      // Inject DIV into target, this is our game board
      $(targetElement).html(
        "<div id = ‘board’></div>"
      );

      $("#board").css({
        position:‘absolute’,
        width: boardSize,
        height: boardSize,
        border: ‘1px solid gray’
      });

      // Populate the game board’s HTML container with 15 squares
      for (var i = 0; i < 16; i++)
      {
        // A  dirty way to create an arbitrary DIV and
        // append it into HTML dynamically
        // Notice each square uses the same image monalisa.jpg
        // It just uses a different x/y offset for each square
        $("#board").append(
          "<div style=’" +
            "position: absolute;" +
            "left: " + ((i % 4) * square_size) + "px;" +
            "top: " + Math.floor(i / 4) * square_size + "px;" +
            "width: " + square_size + "px;" +
            "height: " + square_size + "px;" +
            "text-align: center;" +
            "line-height: 128px;" +
            "-moz-box-shadow: inset 0 0 20px #555555;" +
            "-webkit-box-shadow: inset 0 0 20px #555555;" +
            "box-shadow: inset 0 0 20px #555555;" +
            "background: #ffffff url(monalisa.png) " +
              ((i % 4) * square_size) + "px "
              + Math.floor(i / 4) * square_size + "px " +
              "no-repeat !important’>" +
        "</div>");
      }

      // Empty up the 16th square, as the starting point
      // EmptySquare = 16
      $("#board")
        .children("div:nth-child(" + EmptySquare + ")")
        .css({
          backgroundImage: "",
          background: "#ffffff"
        });

      // Attach click event to each square
      $("#board").children("div").click(function() {
        Move(this, square_size);
      });
    }
  });

  // Move() is the function that is called when a square is clicked
  // Note that it is independent of the plugin itself which is described above
  // It takes two parameters,
  //     1. object handle to the square that was clicked, and
  //     2. the width of the square
  function Move(clicked_square, square_size)
  {
    // We need to locate movable tiles based on where the empty spot is,
    // We can only move the four surrounding squares
    var movable = false;

    // Swap x/y between the clicked square and the currently empty square
    var oldx = $("#board")
      .children("div:nth-child(" + EmptySquare + ")")
      .css("left");
   
    var oldy = $("#board")
      .children("div:nth-child(" + EmptySquare + ")")
      .css("top");

    var newx = $(clicked_square).css("left");
    var newy = $(clicked_square).css("top");

    // The clicked square is north of the empty square
    if (oldx == newx && newy == (parseInt(oldy) square_size) + ‘px’) {
      movable = true;
    }

    // The clicked square is south of the empty square
    if (oldx == newx && newy == (parseInt(oldy) + square_size) + ‘px’) {
      movable = true;
    }
       
    // The clicked square is west of the empty square
    if ((parseInt(oldx) square_size) + ‘px’ == newx && newy == oldy) {
      movable = true;
    }
       
    // The clicked square is east of the empty square
    if ((parseInt(oldx) + square_size) + ‘px’ == newx && newy == oldy) {
      movable = true;
    }
   
    if (movable)
    {
      // Increment zindex so the new tile is always on top of all others
      $(clicked_square).css("z-index", zi++);

      // Swap squares… Animate new square into old square position
      $(clicked_square).animate({ left: oldx, top: oldy }, 200, function()
      {
        //Move old square into new square position
        $("#board")
          .children("div:nth-child(" + EmptySquare + ")")
          .css("left", newx);
       
        $("#board")
          .children("div:nth-child(" + EmptySquare + ")")
          .css("top", newy);
      });
    }
  }

  // Ok, we’re ready to initialize the game, let’s do it.
  // Create a game with 128 by 128 squares inside "#target" div:
  $("#target").fifteen(128);
});

With the page looking like:

<html>
  <body>
    <!– This is where the game will be injected //–>
    <div id = "target"></div>
  </body>
</html>

I tried to explain the code to the best of my ability here but some details were skipped because there is so much more to JavaScript.

If you feel like you still need to understand what some of the things mean I recommend grabbing a copy of my jquery tutorial book which contains a multitude of tutorials and visual diagrams. They are designed to help you build your understanding of JavaScript and jQuery so you can write your own plugins, games, etc.

I hope you enjoyed this tutorial and perhaps learned a thing or two.

Node.js and Express – Setting Content-Type for all Responses

If you’re using Express and Node.js to create an API, it’s likely you’ll want all of the responses to be of a single type, probably JSON. This is easily accomplished by adding a few routes that catch every request, set the content type, and then calling next() to pass the request to the next handler.

// GET
app.get(‘/*’, function(req, res, next) {
  res.contentType(‘application/json’);
  next();
});

// POST
app.post(‘/*’, function(req, res, next) {
  res.contentType(‘application/json’);
  next();
});

// PUT
app.put(‘/*’, function(req, res, next) {
  res.contentType(‘application/json’);
  next();
});

// DELETE
app.delete(‘/*’, function(req, res, next) {
  res.contentType(‘application/json’);
  next();
});

Since Express evaluates routes in the order they are added, these will have to be defined before the more specific ones. In this example, every request made to the application will first be caught by these handlers and then passed on using the next() function.

Another way to accomplish this is by providing some custom middleware. The use function defines a function that will be called in the process of completing a request. This will need to be executed before the routes are defined.

app.use(function(req, res, next) {
  res.contentType(‘application/json’);
  next();
});

In this example, every request that comes into Express will pass through this function. We have to the ability to do whatever we want with it before continuing. In this case, setting the content type.

Node.js Hosting Solutions

Node.js is growing like crazy, and with that popularity comes companies offering platforms to host those applications. The ecosystem is still young, but below is a list of the companies I’ve found that offer a home for your Node.js projects.

Nodejitsu

http://nodejitsu.com

Nodejitsu is currently the leading name in the Node.js platform service provider space. Their PAAS offering is lightweight, but functional. One neat feature they offer is the ability to rollback to previous versions of your application.

Status: Public Beta
Deploy: Web, CLI
Scaling: Multiple Drones


Modulus

http://modulus.io

Modulus is new to the Node.js PAAS space and focuses heavily on providing metrics surrounding your application and its performance. They also provide integrated disk access that’s shared across all instances of your app.

Status: Private Beta
Deploy: Web
Scaling: Multiple Servos


Cloudnode

http://cloudno.de

Cloudnode is built on top of Nodester’s open-source stack. They offer integrated access to CouchDB and Redis.

Status: Private Beta
Deploy: Git
Scaling: Not yet


Nodester

http://nodester.com

Nodester’s entire infrastructure is open source. Almost all interactions with the service will be done through the CLI and their hosting offering is extremely lightweight.

Status: Private Beta
Deploy: Git
Scaling: Not yet


Nodesocket

http://nodesocket.com

Node.js apps in Nodesocket are run inside dedicated VMs. Control over your apps are done entirely through a REST service.

Status: Private Beta
Deploy: Git, SFTP
Scaling: None


Appfog

http://appfog.com

Appfog takes a very different approach to provisioning resources for your applications. Customers allocate a global amount of memory and then fit as many instances as they can by adjusting the amount of memory per instance. They’ve been for around, started with PHP, and have recently added Node.js.

Status: Public
Deploy: CLI
Scaling: Multiple Instances


Heroku

http://heroku.com

If you’re looking into PAAS, you’ve heard of Heroku. They made their name by hosting Rails apps and have recently expanded to several other platforms.

Status: Public
Deploy: Git
Scaling: Multiple Dynos


Azure Websites

http://windowsazure.com

Microsoft has been expanding quickly into the IAAS and PAAS spaces. Azure Websites is their PAAS offering and supports Node.js as well as other frameworks.

Status: Public Beta
Deploy: Git, TFS, FTP
Scaling: Multiple instances


This is the list I could find through my normal searching, but I know there are more. If I missed any, drop them in a comment so we can all check them out.

Aug 8th – Node.Cincy Begins!

Are you a Node.js developer with callbacks that are getting out of hand? Maybe you are a JavaScript developer who wants to learn more about Node? Or maybe you are just looking to meet other developers for beer and pizza? Whatever the case, you need to come down to The Brandery for the first ever Node.Cincy meetup.

Sponsored by Modulus, Jetpacks for Dinosaurs (providing some books to give away), and The Brandery, Node.Cincy will be a collection of developers getting together to learn and talk about all things Node.js. If you are any sort of web developer, this is the meetup for you.

Head over to the meetup to find out more, and we hope to see you there!

When: August 8th, 7:00PM

Where: The Brandery

1411 Vine Street
Cincinnati, OH 45202
Goto Google Maps

What: Node user group, free beer and pizza

Posting JSON data with Node.js

More than likely your Node.js application is acting like some sort of web service. Every once in a while your web service needs to communicate with another one. In this tutorial I’m going to demonstrate how to invoke an HTTP request using Node.js and post some JSON data to it.

My assumption for this article is that you’ve already got a Node.js application up and running, so I’m going to skip most of the boilerplate code and get right to the important stuff. The first thing we’ll need is some data to post, which you’ve probably already got, but here’s mine.

var user = {
  username: ‘The Reddest’,
  email: [email protected],
  firstName: ‘Brandon’,
  lastName: ‘Cannaday’
};

You can post data in several ways, but the most common and what we’re going to use is string data. Fortunately it’s super simple to convert an object into a string using the built-in JSON class.

var user = {
  username: ‘The Reddest’,
  email: [email protected],
  firstName: ‘Brandon’,
  lastName: ‘Cannaday’
};

var userString = JSON.stringify(user);

Now we need to tell the remote server what kind of data we’re sending, in the form of headers.

var user = {
  username: ‘The Reddest’,
  email: [email protected],
  firstName: ‘Brandon’,
  lastName: ‘Cannaday’
};

var userString = JSON.stringify(user);

var headers = {
  ‘Content-Type’: ‘application/json’,
  ‘Content-Length’: userString.length
};

The “Content-Type” header tells the remote server we’re going to be sending a JSON string. The “Content-Length” is just the number of characters we’re sending. If you’re sending files, this field will be how large the file is, in bytes.

Next up we need to specify what server we want to talk to and how we’re going to do it. This is done using a simple options object. This object will be supplied to Node.js when we make the actual request.

var user = {
  username: ‘The Reddest’,
  email: [email protected],
  firstName: ‘Brandon’,
  lastName: ‘Cannaday’
};

var userString = JSON.stringify(user);

var headers = {
  ‘Content-Type’: ‘application/json’,
  ‘Content-Length’: userString.length
};

var options = {
  host: ‘myServer.example.com’,
  port: 80,
  path: ‘/user/TheReddest’,
  method: ‘POST’,
  headers: headers
};

In my example I’m going to post data to myServer.example.com:80/User/TheReddest. Notice that there is no leading ‘http://’ in front of the host – DO NOT add a leading ‘http://’ to the host.

Now it’s time to make the actual request. Fortunately Node.js makes this pretty easy.

var http = require(‘http’);

// Setup the request.  The options parameter is
// the object we defined above.
var req = http.request(options, function(res) {

});

So far, we haven’t actually done anything. We still need to write our data to the request and read the response. Let’s start with writing our data.

var http = require(‘http’);

// Setup the request.  The options parameter is
// the object we defined above.
var req = http.request(options, function(res) {

});

req.write(userString);
req.end();

At this point, the remote server will received your posted data. All that’s left is to read the response. This is done inside the callback that’s supplied to the http.request function.

var http = require(‘http’);

// Setup the request.  The options parameter is
// the object we defined above.
var req = http.request(options, function(res) {
  res.setEncoding(‘utf-8’);

  var responseString = ;

  res.on(‘data’, function(data) {
    responseString += data;
  });

  res.on(‘end’, function() {
    var resultObject = JSON.parse(responseString);
  });
});

req.write(userString);
req.end();

The response that comes back from the remote server can appear in multiple chunks. This means the ‘data’ callback may be invoked multiple times. The responses do come back in order, so all we have to do is append all the responses together into a single string. The ‘end’ callback will be invoked when everything has been received. The remote server you’re connecting to may or may not return JSON, but in my example it does, so I simply use JSON.parse to convert it into a usable object.

The last thing you’ll probably want to do is handle errors. This is done by simply hooking the ‘error’ event on the request object.

var http = require(‘http’);

// Setup the request.  The options parameter is
// the object we defined above.
var req = http.request(options, function(res) {
  res.setEncoding(‘utf-8’);

  var responseString = ;

  res.on(‘data’, function(data) {
    responseString += data;
  });

  res.on(‘end’, function() {
    var resultObject = JSON.parse(responseString);
  });
});

req.on(‘error’, function(e) {
  // TODO: handle error.
});

req.write(userString);
req.end();

Just for good measure, here’s all the code in one piece:

var http = require(‘http’);

var user = {
  username: ‘The Reddest’,
  email: [email protected],
  firstName: ‘Brandon’,
  lastName: ‘Cannaday’
};

var userString = JSON.stringify(user);

var headers = {
  ‘Content-Type’: ‘application/json’,
  ‘Content-Length’: userString.length
};

var options = {
  host: ‘myServer.example.com’,
  port: 80,
  path: ‘/user/TheReddest’,
  method: ‘POST’,
  headers: headers
};

// Setup the request.  The options parameter is
// the object we defined above.
var req = http.request(options, function(res) {
  res.setEncoding(‘utf-8’);

  var responseString = ;

  res.on(‘data’, function(data) {
    responseString += data;
  });

  res.on(‘end’, function() {
    var resultObject = JSON.parse(responseString);
  });
});

req.on(‘error’, function(e) {
  // TODO: handle error.
});

req.write(userString);
req.end();

And there you have it. This tutorial demonstrates how to POST JSON data to a remote server using Node.js. If you have any questions or comments feel free to leave them below.

Javascript Tutorial – Design for Testability

If you’ve ever built a client/server application, you know how tedious it can be get access to a working server in order to test client functionality. With the right design, however, this is a headache we don’t have to experience. This approach was used by our team recently when developing the Facebook game, Tic-Tac-Together, and proved to be quite successful.

The root of this design involves encapsulating the communication layer into separate objects, which you should be doing anyway. Putting communication logic directly in your higher-level code is just asking for future maintenance difficulties. For Tic-Tac-Together (TTT) we needed two communication objects: one for our server and one for the Facebook API. Below is a snippet of each class with the implementations removed.

//
// Server Class
//
ttt.Server = function() {

};

// Connects to the server.
ttt.Server.prototype.connect = function(url, callback) {
  // All the logic required to connect to the TTT server.
};

// Gets a user based on their facebook ID.
ttt.Server.prototype.getUser(facebookId, callback) {
  // Sends a get user request to the server.
};

//
// Facebook class
//
ttt.Facebook = function() {

};

// Initializes the facebook interface.
ttt.Facebook.prototype.init = function(apiKey) {
  // Initialize the Facebook JS SDK.
};

Normally I’d write all of the implementation here and then wait around for a server to become available to test if anything worked. What we’re going to do instead is create two copies of each class with the exact same signature. The live version will do real communications, and the fake version will do whatever we need it to for local testing.

//
// Test Server Class
//
ttt.test.Server = function() {

};

// Connects to the server.
ttt.test.Server.prototype.connect = function(url, callback) {
  // Don’t actually need to do anything, just raise the callback.
  if(callback) {
    callback();
  }
};

// Gets a user based on their facebook ID.
ttt.test.Server.prototype.getUser(facebookId, callback) {
  var user = new ttt.model.User();
  user.name = "Test User";
  user.id = 1;

  if(callback) {
    callback(user);
  }
};

//
// Test Facebook class
//
ttt.test.Facebook = function() {

};

// Initializes the facebook interface.
ttt.test.Facebook.prototype.init = function(apiKey) {
  // Don’t actually need to do anything here.
};

The only difference between the signatures is that I put the two new classes in another namespace, test. As you can see, the test versions of these classes don’t do any actual server communication. When connecting to the server, the client is immediately notified by raising the callback. When initializing the Facebook API, the test code doesn’t even have to do anything. When requesting a user, the test class generates a user and immediately returns it to the calling code. This is a very powerful aspect of this design – when testing locally I can change the data being returned from the test objects to whatever I need in order to fully exercise the client code.

Since the live and test versions share the same signatures, code that calls them does not have to know which version is being used. When you want to toggle between local testing and live testing, simply construct the appropriate version of the class.

var server = new ttt.test.Server();  // Test version.
//var server = new ttt.Server();  // Live version.

var facebook = new ttt.test.Facebook(); // Test version.
// var facebook = new ttt.Facebook(); // Live version.

facebook.init();

server.connect(function() {
  alert(‘connected’);
});

server.getUser(10, function(user) {
  alert(‘name: ‘ + user.name);
});

As seen above, the server and facebook variables can either be the live version or the test version. The code beneath their initialization doesn’t care at all.

Having to maintain two versions of the same class has proved to be irritating, but the benefits are well worth it. If you’re using a classical inheritance scheme, like John Resig’s, you could create base classes for each communication object and extend them for the live and test versions. That approach has benefits and leads to a more flexible design – you could easily add multiple test objects and override individual functions for different behavior.

There are lots of possible variations on this design, but what you should remember is the core idea. When designing your system, include the ability to run your client code without requiring a live (and properly functioning) server. If you have any questions, feel free to drop them below. If you’re waiting for your code to compile, you should also challenge someone to a friendly game of Tic-Tac-Together.

Top 10 jQuery Plugins for Programmers

We all love jQuery. Its a simple fact that it provides powerful tools to get your JavaScript done right. However, one of its most powerful features is its extensiblity, and many developers have taken full advantage of this. This has created plenty of plugins to choose from, and today we are going to look at some of our favorite ones to hit the scene.

#10: jQuery UI

Site | Demo

This is one of the most extensive and flexible JavaScript UI frameworks out there. jQuery UI offers up everything from simple yet fancy buttons to complete accordions and autocompletes. It also has a pretty simple and powerful dialog framework that makes popups a snap. However, the best part about the whole deal is that you can create your very own theme right on the website, to fit your style, complete with custom-colored images and all.

Quick Snippet:

<div id="dialog" title="Basic dialog">
  <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the ‘x’ icon.</p>
</div>
$( "#dialog" ).dialog();

#9: Roundabout

Site | Demo

Sliders are not only one of the most popular ways to fancy up a dull site, but they can be quite a tedious pain to implement. There are plenty of options to choose from when it comes to plugins in this area, but the Roundabout is one of the best. It offers a neat style and is quite easy to get up and get running. It’s also flexible enough to morph into other uses, such as animations or a neat way to pick form values.

Quick Snippet:

<ul id="myRoundabout">
  <li><span>Block 1</span></li>
  <li><span>Block 2</span></li>
  <li><span>Block 3</span></li>
  <li><span>Block 4</span></li>
  <li><span>Block 5</span></li>
</ul>
$(‘ul#myRoundabout’).roundabout();

#8: Slides

Site | Demo

While Roundabout offers a neat, new-age way to rotate through summary-type content, sometimes you need something a bit less fancy. This is where slides comes in. It will give you an easy option for “sliding” between content, but is open enough to give you control over the things you want, such as style and transitions. To top it all off, it gives you paging right out of the box, which is always nice to have for sliders.

Quick Snippet:

<div id="slides">
  <div class="slides_container">
    <div>
      <h1>Slide 1</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>
    <div>
      <h1>Slide 2</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>
    <div>
      <h1>Slide 3</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>
    <div>
      <h1>Slide 4</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>
  </div>
</div>
$("#slides").slides();

#7: Simple Modal

Site | Demo

One thing that makes Simple Modal attractive is its name sake…its simplicity. Its lightweight and requires very little setup to get going. Some modals out there require a lot of elements to be on the page or complicated style setup, but not Simple Modal. However, like any self-respecting plugin, all of the setup is exposed, so if you really want to go overboard with styles and just animations, you can.

Quick Snippet:

$.modal("<div><h1>SimpleModal</h1></div>");

#6: qTip2

Site | Demo

When you need tooltips and mouseovers to be exactly what you want, in the position that you want, the style that you want, qTip2 is your unequivocal answer. It offers not only a comprehensive list of options, but comes with some pretty snazzy styles right out of the box. You can also load all kinds of content inside your tooltips as well, from simple text or images to AJAX retrieved data. If you include qTip2 in your jQuery project, you will probably never need another solution for useful tooltip feedback.

Quick Snippet:

$(‘a[title]’).qtip();

#5: jquery.cookie

Github

Despite the chocolate-chipy goodness we all want to think about right now, web cookies are still an important part of our developer lives. Pretty much any modern website uses them in some capacity. Luckily, using jQuery and the jquery.cookie plugin, accessing them via JavaScript is a breeze. A great example of a simple, effective solution.

Quick Snippet:

$.cookie(‘the_cookie’, ‘the_value’);
$.cookie(‘the_cookie’); // => ‘the_value’

#4: ColorBox

Site | Demo

Lightbox is an extremely powerful popup library for displaying and organizing media, with a lot of different offshoots to choose from. ColorBox is one of the offshoots. The difference is that it is designed to not only be lightweight and work with jQuery, but it is also extremely easy to customize it to the looks you want. Some of these types of plugins can be very complex, but luckily you have ColorBox on your side to simplify things up for you.

Quick Snippet:

<a class="group1" href="../content/ohoopee1.jpg" title="Me and my grandfather on the Ohoopee.">Grouped Photo 1</a>
<a class="group1" href="../content/ohoopee2.jpg" title="On the Ohoopee as a child">Grouped Photo 2</a>
<a class="group1" href="../content/ohoopee3.jpg" title="On the Ohoopee as an adult">Grouped Photo 3</a>
$(".group1").colorbox({rel:‘group1’});

#3: jQuery Mouse Wheel

Github

In straight JavaScript, handling the mouse wheel event can be tricky at best. To make things worst, jQuery does not have native support for getting the mouse wheel event. This is where the mouse wheel plugin comes in. It literally just adds a bindable event to jQuery so you can hook into the mouse wheel scroll event, for all your wheel scrolling pleasure.

Quick Snippet:

$(‘#my_elem’).bind(‘mousewheel’, function(event, delta, deltaX, deltaY) {
    console.log(delta, deltaX, deltaY);
});

#2: jQuery Validation

Site | Demo

Validation is one of those necessary things that can require a lot of time. From creating complex regular expressions, to styling things to make errors obvious to the user, it can be quite a task. With all this in mind, it is quite amazing when you see how much of this can be accomplished with jQuery Validation, with a very minimal effort. It even hooks in some custom selectors to help you keep track of all your validated elements. You are not going to find a more comprehensive validation solution for jQuery, hands down.

Quick Snippet:

<form id="commentForm" method="get" action="">
    <fieldset>
    <p>
      <label for="cname">Name (required, at least 2 characters)</label>
      <input id="cname" name="name" class="required" minlength="2" />
    </p>
    <p>
      <label for="cemail">E-Mail (required)</label>
      <input id="cemail" type="email" name="email" class="required" />
    </p>
    <input class="submit" type="submit" value="Submit"/>
  </fieldset>
</form>
$("#commentForm").validate();

#1: Tablesorter

Site | Demo

Most solutions for handling tables and the data therein are server/client-side meshes that provide a good way to show and organize data. The only issue with that is speed, which can suffer if you have such a complex solution. Tablesorter helps to aliviate some of this issue by, well, helping you sort your tables on the client-side. It can sort a lot of options for sorting all kinds of data, and has a pleasingly simple design. A great addition to any data-driven interface.

Quick Snippet:

<table cellspacing="1" class="tablesorter">            
  <thead>
    <tr>
        <th>first name</th>
        <th>last name</th>
        <th>age</th>
        <th>total</th>
        <th>discount</th>
        <th>date</th>
    </tr>
  </thead>
    <tbody>
    <tr>
      <td>peter</td>
      <td>parker</td>
      <td>28</td>
      <td>$9.99</td>
      <td>20%</td>
      <td>jul 6, 2006 8:14 am</td>
    </tr>
    <tr>
      <td>john</td>
      <td>hood</td>
      <td>33</td>
      <td>$19.99</td>
      <td>25%</td>
      <td>dec 10, 2002 5:14 am</td>
    </tr>  
  </tbody>
</table>
$("table").tablesorter();

So there you have it. Ten awesome jQuery plugins that will help you in just about any situation you may find yourself in. That is the beauty of something as robust as jQuery, you can always find an easy to use and quick to implement solution for the problem at hand.

So this wraps it up for now. Just remember, if you need coding help, all you have to do is Switch On The Code.

Pulse v1.0 Released

We’ve been hard at work and the effort has paid off. As of today, Pulse is ready for the mainstream. We’ve open-sourced the project and we’ve chosen the MIT license, which gives devs a lot of flexibility in how they use the framework.

There’s still a lot of work that needs to get done, like making the website better, more supporting documentation, and definitely some example games, but none of that is needed for you to download and begin using Pulse.

Even though it’s released, we’re nowhere near done with it. We’ve got an endless backlog of awesome features that we’re dying to add, and Pulse will only get better as we continue to improve it.

As you use the framework, we want to hear what you think. Even if it’s the most minor feature request or question, we don’t care, drop us a line.

Javascript Snippet – Tables and innerHTML

In a previous tutorial we showed you how to dynamically add and remove rows from a table. This is a very useful technique, but sometimes you might need to add entire bits of HTML into a table as just a string. In this situation, things can get a little tricky.

Let’s say you have a table, and you need to insert HTML into it. Either you have a AJAX call that returns a string of HTML, or you just like slapping HTML into a table. Sometimes that’s just what you have to do. In the tutorial mentioned above, DOM methods were used to insert rows. While this is the preferred and suggested method, from time to time you end up with this situation:

var html = ‘<tr><td>Some Data</td></tr>’;
var table = document.getElementById(‘myTable’);

table.innerHTML += html;

Now, this may seem like the perfect way to do things, but there are several problems. First off, most browsers require and even add a tbody tag. So right off the bat we are selecting the wrong element to add our HTML to.

However, that isn’t the biggest problem we will run into. In Internet Explorer, innerHTML is read only on tables. Yeap, read only. Since we all like to be cross-browser compatible, the solution above is unacceptable.

At this point, using jQuery would be a good option, as it would allow you to convert an HTML string into something you can append to the table. At the very least it provides more enhanced tools for dealing with tables, as well having hoards of plugins for this exact kind of task.

That being said, all you will be doing with jQuery is converting the string into usable DOM objects, and if you absolutely have to do it with plan ol’ javascript, it is possible (of course). It actually only takes a few simple lines of Javascript:

var html = ‘<tr><td>Some Data</td></tr>’;
var table = document.getElementById(‘myTable’).getElementsByTagName(‘tbody’)[0];
var tmpTable = document.createElement(‘div’);
tmpTable.innerHTML = ‘<table><tbody>’ + html + ‘</tbody></table>’;
var tr = tmpTable.getElementsByTagName(‘tr’)[0].cloneNode(true);
table.appendChild(tr);

Basically what we are doing is creating a temporary table to convert our string into usable DOM objects. We do this by setting the innerHTML of div (which we create), which allows use to then get our original table row as a DOM object. From there it’s as easy as appending it to our table body.

So there you have it, converting a string to DOM objects for use in a table. That wraps it up for this tutorial. Just remember, when you need coding help all you have to do is Switch On The Code.

HTML 5 Canvas Tutorial – Drop Shadows

While working on the Pulse graphics engine I’m learning all kinds of new techniques and tid bits about Canvas. One of the latest things I’ve been playing around with and working on is creating shadows. This is actually pretty easy with the JavaScript drawing api available for canvas. It actually just takes a few properties set on the canvas context.

Before jumping into the code there are a couple of items to note. First, you can selectively apply a shadow by using the save and restore methods on the context. Second, for performance reasons make sure to draw shadows as infrequently as you can. Now let’s jump into the code.

function bodyloaded() { // Attached to body’s onload event

  var canvas = document.getElementById(‘myCanvas’); // Grabs the canvas element
  var ctx = canvas.getContext(‘2d’); // Grabs the canvas context

  ctx.save(); // Save the state of the context
  ctx.fillStyle = ‘#4433FC’; // Sets the fill color
  ctx.shadowOffsetX = 2; // Sets the shadow offset x, positive number is right
  ctx.shadowOffsetY = 2; // Sets the shadow offset y, positive number is down
  ctx.shadowBlur = 4; // Sets the shadow blur size
  ctx.shadowColor = ‘rgba(0, 0, 0, 0.6)’; // Sets the shadow color
  ctx.beginPath(); // Starts a shape path
  ctx.arc(150, 150, 75, 0, 2 * Math.PI, false); // Draws a circle
  ctx.fill(); // Fills the path
  ctx.restore(); // Restore the state of the context

  ctx.fillStyle = ‘#DE33FC’; // Sets the fill color
  ctx.beginPath(); // Starts a shape path
  ctx.arc(350, 350, 60, 0, 2 * Math.PI, false); // Draws a circle
  ctx.fill(); // Fills the path
}

That’ll spit out something like the following.

Looking at the code it starts out by grabbing the canvas and then the context from the canvas. In order to apply the drop shadow to only a part of the canvas we have to use the save and restore functions on the context. The next thing done is to set the appropriate properties on the canvas context.

  • shadowOffsetX – the horizontal offset for the drop shadow
  • shadowOffsetY – the vertical offset for the drop shadow
  • shadowBlur – the size of the blur of the drop shadow
  • shadowColor – the color of the drop shadow

At a minimum the shadowBlur and shadowColor properties have to be set in order for the shadow to be used. The color can be set with any of the formats available for fill style or stroke color. I’d recommend using the ‘rgba’ format so you can set the alpha on the color.

That wraps it up for this tutorial. Make sure to check out some of other canvas tutorials here on the site. If you have any questions or comments, feel free to leave them below.

If you’re looking for more information on HTML5 Canvas. Check out these great books: