Node.js

Our games will need to be served from something besides a static web server if we want to have any online features. Our goals will be to use Node.js to build a server application in JavaScript. It will communicate with our game (the client) to pass along content or messages regarding player profile information, scores, etc. We will then later host our server application on a website such as Heroku, and communicate with a database such as MongoDB.

Overview

  • Node.js is a JavaScript environment that runs on the server, ie. outside of the browser.
  • Many alternatives: Python, PHP, Ruby. But Node is pretty popular, cross-platform and lightweight.
  • Excellent for real-time multiplayer, since it would allow us to share code between client and server!
  • Nonblocking I/O, because it is single threaded (not all server environments are like this). More event based programming through callbacks!
  • Only provides a minimal baseline of functionality for processessing web requests.
  • Extended through modules, lots of them out there made by various different people. We will use one module called Express, which is a web application framework (let's us build an HTTP server with ease).

General Uses

  • Write a server application using JavaScript (which has typically been a client-side only language)
  • Server application can handle web requests from our game and can communicate with a database, allowing us to build out our online services such as player profiles, achievements, leaderboards, etc.
  • Can be used locally (not on web server) to run command line scripts to aid in development - package and minify our game, sprite packing tool, etc.
  • Chapter 8 has a nifty Node.js module for generating sprite sheets, which we will not be going over. Node-canvas is a neat way to let the server create procedural images and send them to the client.

Book Notes

  • Node.js is covered in Chapter 8 and Chapter 19 of the book
  • Chapter 8 - Installing Node.js, using it locally for build tools and image processing.
    • Read over this chapter to understand how Node.js works with modules and building an application. Particularlly Learning about Node.js, Installing Modules, and Creating a package.json file.
    • It covers installing Node.js for various platforms in a way that includes the development environment so that we can compile modules that only have native source code. We do not need this in our class, so you can ignore this and just use the installer!
    • It also covers building a local module
  • Chapter 19 - Serving a game and its content through a Node.js server application, sending user generated content back to the server.
    • The section covers building a basic server application in Node.js, which is important. It also builds a level editor for the platform game it covers in the previous chapter, which we are not concerned about.

Installing

  • Go download a Node.js installer here - http://nodejs.org
  • Run the installer. DONE!
  • Now node is available from your command line:
     > node

Package Manager

Chapter 8, page 136

  • > npm
    Node Package Manager - provides an automated way to download and install libraries and utilities (it comes installed with Node.js)
  • By default, node modules are installed locally for whatever directory you are in (usually your project's folder). Install them globally to make that module's binary accessible from the command line.
  • Examples:
    > npm install --global jshint
    > npm install --global uglify-js
    > npm install --global express

Our first Node.js application

Chapter 8, pages 138

Chapter 19, pages 371-373

  • Let's build a basic webserver that we can run locally and will server static files. You could use this instead of Mongoose, Windows IIS, Apache, etc.
  • Serving static files to a user requires we add a module. There are a few choices, but we'll be going with Express.
    • Express has a lot of great features over other modules: views, caching, routing, sessions, and serving static files.
    • General life saver vs. using Node.js by itself

package.json

A file that Node Package Manager uses to get information about your module or application and its dependencies.

  • Fields: name, description, author, version, dependencies, main application JS file
    {
    	"name": "html5_webhost",
    	"version": "0.0.1",
    	"private": true,
    	"dependencies": {
    		"express": "2.5.8",
    		"jade": ">= 0.0.1",
    		"underscore": "1.3.3"
    	}
    }
    
    

app.js

A boilerplate Express application:

  • Loads a few module dependencies (fs, underscore)
    // Load our dependencies
    var express = require('express'),
    	fs = require('fs'),
    	_ = require('underscore');
    
  • Creates an Express server that we can customize
    // Our app module is going to a customized express server
    var app = express.createServer();
    
  • Sets up the server to parse incoming POST messages, and use a /public directory as the location to serve static assets from
    // The server will be serving static files from a sub directory called "/public"
    app.configure(function(){
    	app.use(express.bodyParser());
    	app.use(express.static(__dirname + '/public'));
    });
    
  • Sets up error handlers
    // Set different error handlers for different environments
    // Default environment is development
    app.configure('development', function(){
    	app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
    });
    
    app.configure('production', function(){
    	app.use(express.errorHandler());
    });
    
  • Starts the server on a specific port.
    // Start the server!
    app.listen(3000, function(){
    	console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
    });
    
  • Return our new Application module
    // Return our App module
    module.exports = app;
    

Running your webserver

  • Put some files into your /public folder, like an "index.html". You could put your whole game into this folder!
  • Install the necessary dependencies. Node Package Manager will install them locally into a directory called "node_modules"
    > npm install
    
  • Run your application
    > node app.js
    
  • Test your application http://localhost:3000/