This post is sponsored by PubNub, a Node Knockout 2013 service sponsor.

PubNub allows you to connect mobile phones, tablets, web browsers, and more with a two function publish/subscribe API (send/receive). You can read more on our How It Works page.

First, you’ll need to create a PubNub account. This will give you access to all our APIs, keys, and PubNub features.

Quick Start Step 1

If you’re building HTML5 web apps, start by copying and pasting the code snippet below. If not, skip to Step 2:

Read More

This post was written by Passport creator Jared Hanson.

Passport is middleware for Node.js that makes implementing authentication quick and easy. Authentication can take a variety of forms, including a username and password, OpenID, OAuth, and BrowserID.

Many users prefer to sign in using an existing social network account, such as Facebook or Twitter. In this example, we’ll implement support for signing in with Twitter.

Install Dependencies

$ npm install express
$ npm install passport
$ npm install passport-twitter
$ npm install connect-ensure-login

We’ll be building on the simple Express application that TJ Holowaychuk built in an earlier post. Passport has a modular architecture that breaks authentication mechanisms into strategies (in this case Twitter) which are distributed separately, keeping the core lightweight. We’ll also use connect-ensure-login to protect authenticated routes.

Authentication Checklist

The following three items need to be checked off to implement authentication.

  1. Configure session middleware
  2. Configure authentication strategies
  3. Add authentication routes

We’ll cover each of them, starting from outside in: routes to middleware.

Authenticated Routes

Let’s add a route to /account, which shows a person their account details.

app.get('/account',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.send('Hello ' + req.user.username);
  });

In order to access this page, a user will need to be logged in. ensureLoggedIn will verify that this is the case, and if not, redirect the user to the login page. Which looks like:

app.get('/login',
  function(req, res) {
    res.send('<html><body><a href="/auth/twitter">Sign in with Twitter</a></body></html>');
  });

Simple. The user can just click a link and sign in with Twitter. Which brings us to the next step in our implementation:

Configuring Twitter Authentication

Twitter authentication uses OAuth, which means you’ll need to obtain a key and secret from Twitter. If you don’t have one yet, you’ll need to register your application with Twitter.

Once you have keys, configure the Twitter authentication strategy:

var TWITTER_CONSUMER_KEY = "INSERT_KEY_HERE";
var TWITTER_CONSUMER_SECRET = "INSERT_SECRET_HERE";

passport.use(new TwitterStrategy({
    consumerKey: TWITTER_CONSUMER_KEY,
    consumerSecret: TWITTER_CONSUMER_SECRET,
    callbackURL: "http://127.0.0.1:3000/auth/twitter/callback"
  },
  function(token, tokenSecret, profile, done) {
    // NOTE: You'll probably want to associate the Twitter profile with a
    //       user record in your application's DB.
    var user = profile;
    return done(null, user);
  }
));

The function supplied to the strategy is known as a “verify callback”. Verify callbacks receive credentials as arguments (in this case the token, tokenSecret and profile), which are used to locate and return user records. The user instance returned will be logged in and set on the request at req.user.

In most applications, you’ll want to associate the Twitter account with a user record in your application’s database. This allows you to also associate other accounts (such as Facebook) with the same user, allowing them to log in using either service. To keep this example simple, we will use the profile data directly, avoiding the need for database associations.

The OAuth protocol used by Twitter involves a two-step process using redirects to exchange and verify tokens. This is fairly complicated, but Passport middleware makes it easy. Just drop in the following routes:

app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback', passport.authenticate('twitter', { successReturnToOrRedirect: '/', failureRedirect: '/login' }));

The first route will begin an OAuth transaction and redirect the user to Twitter. Once signed in, Twitter will redirect the user back to our application and Passport will return them to the original page they requested (or ‘/’).

Easy enough, but there’s still one more thing to do:

Configure Sessions

In order to keep track of the fact that a user has logged in, an application needs to implement support for sessions. Do that by using Express’ built-in cookie parser and session middleware, and initializing Passport.

app.use(express.cookieParser());
app.use(express.session({ secret: 'keyboard cat' }));
app.use(passport.initialize());
app.use(passport.session());

When a user logs in, the user record is stored in the session in order to maintain the logged-in state as she browses your site. Serialization and deserialization functions are supplied to control this process.

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});

As noted above, if you are creating user records in your own database, you can serialize just the user ID to minimize the amount of data stored in the session. For simplicity, the entire record is serialized in this example.

Wrapping Up

That’s it, people can now sign in with Twitter! The complete code for this example is available as a gist.

If you take authentication further, consult guide for in-depth details on how Passport operates. Additionally, if you need to implement API authentication, see Passport’s sister projects: OAuthorize and OAuth2orize

Overview

This year, we have created an Ubuntu 12.04 (Precise) instance for each Node Knockout team to use during the competition. A huge thanks to Joyent for providing these instances to contestants for Node Knockout (through Nov 30).

We have already configured each of these instances for easy deployment. If you’re lazy, or not interested in devops, all you need to know is:

# get the code
git clone git@github.com:nko4/<team>.git && cd ./<team>/

# fix permissions on deploy key
chmod 0400 ./id_deploy*

# deploy it to http://<team>.2013.nodeknockout.com/
./deploy nko

The rest of this post will explain how these instances are setup. You don’t need to read this, but you might find it useful if you run into problems, or interesting if you want to customize things.

How we setup Ubuntu for NKO

All the Ubuntu configuration happens in the setup-ubuntu.sh script.

Setting the hostname

# set the hostname
hostname=$1
hostname $hostname
echo "$hostname" > /etc/hostname

We set the hostname so that your server knows its name. It’s not strictly necessary, but the default can be pretty ugly.

Installing packages (including node)

# Updating apt packages...
apt-get update

# Installing git...
apt-get install -y git-core

# Installing node...
apt-get install -y python-software-properties python g++ make
add-apt-repository -y ppa:chris-lea/node.js
apt-get update
apt-get install -y nodejs

First, we update all the packages, then install git, since it’s needed for the deploy script.

Next, we install node and npm from a package in the manner recommended by Joyent.

Setting NODE_ENV

# Setting NODE_ENV=production...
echo "export NODE_ENV=production" > /etc/profile.d/NODE_ENV.sh

NODE_ENV should be production on production deployments, so we add a script to /etc/profile.d/ to ensure that is the case.

Setting up SSH

# Setting up the root user .ssh/ dir...
mkdir -p ~/.ssh
chmod 700 ~/.ssh
touch ~/.ssh/authorized_keys ~/.ssh/known_hosts
chmod 600 ~/.ssh/authorized_keys ~/.ssh/known_hosts

# Authorizing the nko4 public key for ssh access...
cat <<EOS > ~/.ssh/authorized_keys
#### BEGIN NKO ORGANIZERS KEY
# DO NOT REMOVE - this allows us to audit teams for cheating
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAu793tQ+5RP8uo9X0WRZituBPZwRgMLxyZf+4MlM2BXxizjSlUtP/gTOHTqkzlimR1r3QOTfJN9dzs6DJZsI9T6gxJB2icjYgmYn5/4lwbry0vgoWNXwqrDkWuuSy/zaQYbbZhF3wGnqwsjR3U96XYNB6hz/ugMDkFF3BLcXvqSj0oY7FN6vdWt7tQ9y4kjkFfWJNXewshxJs8DNXqbolGqo+jvXrbq+Uj2faPKUO9rijZzmaNdKW7CX3PQl0JFWFqefKhQlyCQMoBZ47zcU79jfhYrCfd7+DIDPYAxERotGn8T+qKZbmbWPXFJ5xnFfmI6AYpBtMFeWnGol5B/CNJw== nko4
#### END NKO ORGANIZERS KEY
EOS

# Adding github.com to ~/.ssh/known_hosts...
cat <<EOS >> ~/.ssh/known_hosts
github.com,207.97.227.239 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==
EOS

We create the ssh dir and make sure it has proper permissions. Then we add some recognized keys:

  • We add the Node Knockout organizers’ key to ensure that the organizers have access to the box, so they can audit that no unauthorized code modifications happen during the competition.
  • We add the github public key so that there is no prompting when the deploy script connects to github to fetch the code.

Setting up the deploy user

# Setting up the deploy user...
id deploy || useradd -U -m -s /bin/bash deploy

# Setting up the deploy user .ssh/ dir...
deploy_home=/home/deploy
cp -r ~/.ssh $deploy_home/.ssh
chown -R deploy $deploy_home/.ssh

Rather than run the server as root, we’ll run it as the deploy user.

First, we create the user. The id deploy || part ensures that we don’t try and create a deploy user if one already exists.

Second, we setup the ssh directory for the deploy user in the same way as we did for the root user.

Keeping the server running with runit

We use runit to keep your server running if it crashes or the instance reboots.

Installing runit

# Setting up runit...
apt-get install -y runit

Creating a serverjs service for runit

# Setting runit to run server.js...
mkdir -p /etc/service/serverjs/log

cat <<EOS > /etc/service/serverjs/run
#!/bin/sh
exec 2>&1
. /etc/profile
. $deploy_home/.profile
exec node $deploy_home/current/server.js
EOS
chmod +x /etc/service/serverjs/run

runit creates a service monitor for every directory in /etc/service. To get started, we create a directory there for serverjs.

Then we create a run script in the serverjs directory that tells runit what to do to start the service.

Our run script does a couple things.

  1. It loads /etc/profile and $deploy_home/.profile. Primarily so that any environment variables that people add are passed through to the server. (Remember NODE_ENV=production from earlier?)
  2. It starts the server: node $deploy_home/current/server.js

As you can see, with runit you start your server just like you normally would and it handles all the monitoring automatically.

Logging with runit

# Setting up runit logging...
mkdir -p $deploy_home/shared/logs/server

cat <<EOS > /etc/service/serverjs/log/run
#!/bin/sh
exec svlogd -tt $deploy_home/shared/logs/server
EOS
chmod +x /etc/service/serverjs/log/run

runit also has some nice logging abilities built-in. If you create a run script inside of the log/ directory of your service directory, it will automatically pipe the output from your service into the logging script.

Here we use the runit provided svlogd daemon to output the serverjs logs to $deploy_home/shared/logs/server/. svlogd handles log rotation and timestamping automatically.

Cleaning up runit

# Waiting for runit to recognize the new service...
while [ ! -d /etc/service/serverjs/supervise ]; do
  sleep 5 && echo "waiting..."
done
sleep 1

# Turning off the server until the first deploy...
sv stop serverjs
> $deploy_home/shared/logs/server/current

It takes runit up to 5 seconds to recognize if a folder has been added to /etc/service, so we wait a bit to ensure everything is up and running.

Then, since we don’t want runit to try to keep the server up until the code is first deployed, we shut down the service and clear the logs.

Note: you can’t run rm $deploy_home/shared/logs/server/current because svlogd will not recognize that the log file has been removed, so it won’t create a new one.

Giving the deploy user access to runit

# Giving the deploy user the ability to control the service...
chown -R deploy /etc/service/serverjs/supervise
chown -R deploy $deploy_home/shared

A neat trick with runit is that you don’t need to add sudo privileges to give certain users access to manage services. Instead, all you do is change the permissions on the supervise/ directory. That’s what we do here.

Using runit

runit is fairly simple to use, with commands for start, restart, stop and more. You can find the important ones below:

  • sv restart serverjs - restarts
  • sv start serverjs - starts
  • sv stop serverjs - stops
  • ps -ef | grep runsvdir - to see runit ps logs

See man sv for more info.

How we setup deploying for NKO

Ok! The server’s ready. Now onto our local development machine setup.

We use TJ's deploy shell script to make deploying code repeatable and easy for everyone on the team.

We’ve already added the deploy script to your github repo. Along with a deploy.conf file that configures it for the instance we just setup.

This lets us deploy to the server by just typing ./deploy nko.

Here’s what the deploy.conf looks like:

[nko]
key ./id_deploy
forward-agent yes
user deploy
host $ip
repo git@github.com:nko4/${team}.git
ref origin/master
path /home/deploy
post-deploy npm install && sv restart serverjs
test sleep 5 && wget -qO /dev/null localhost

[nko] is the environment to deploy to. You can have multiple deploy targets, for instance, production and stage.

key ./id_deploy tells the deploy script to use the ssh key we created for your team (and that’s stored in your repo) to connect to your server to deploy.

forward-agent yes tells the deploy script to enable ssh agent forwarding, so it can connect to Github from your server.

user deploy tells the script to connect as the deploy user that we setup above.

host $ip tells the script what ip address to connect to.

repo git@github.com:nko4/${team}.git tells the script to deploy code from your team’s github repo.

ref origin/master tells the script to deploy the code from master. If you want, you can deploy a branch with ./deploy nko origin/mybranch

path /home/deploy tells the script where the code should be stored when it is pulled from github.

post-deploy npm install && sv restart serverjs tells the script to install npm modules and restart the server after the code’s been copied from Github.

test sleep 5 && wget -qO /dev/null localhost will cause the script to roll back the deploy if the web server isn’t responding after 5 seconds.

How we setup the `server.js` for NKO

We also created a server.js file in your Github repo that includes some Node Knockout best practices. Here’s a quick summary.

NKO module

// https://github.com/nko4/website/blob/master/module/README.md#nodejs-knockout-deploy-check-ins
require('nko')('${code}');

The first lines of the server add the nko module, which pings the nko website when the app is correctly deployed to production. This lets us hide the deploy instructions on the website after the team has deployed their app correctly, and also allows us to feature recently deployed apps on the front page of the website during the competition.

Vote KO widget

Vote KO widget

var voteko = '<iframe src="http://nodeknockout.com/iframe/${slug}" frameborder=0 scrolling=no allowtransparency=true width=115 height=25></iframe>';

res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<html><body>' + voteko + '</body></html>\n');

Our Vote KO widget lets people vote for your team from within your web page. Including this widget helps you get as many votes as possible.

Downgrading permissions

// if run as root, downgrade to the owner of this file
if (process.getuid() === 0) {
  require('fs').stat(__filename, function(err, stats) {
    if (err) { return console.error(err); }
    process.setuid(stats.uid);
  });
}

Because we’re running node with runit (and therefore as root initially), node has the chance to bind to the privileged port 80. Once it’s bound though, we downgrade the uid of the process to the owner of the server.js file (our deploy user). This is much more secure than running the server as the root user.

Problems?

If you run into any problems, we’re here to help. Email all@nodeknockout.com or try us on Twitter or at IRC, #nodeknockout channel.

This post is sponsored by Firebase, a Node Knockout 2013 service sponsor.

Getting Started with Firebase

Firebase is a real-time backend for building modern, collaborative web and mobile applications. By replacing the traditional request / response model with a data synchronization approach, you can get apps up and running in minutes. Using Firebase as your backend, your data will be persisted in the cloud and stored as JSON. Whenever your data changes, all clients will be notified in real-time. Apps built with Firebase can be written entirely with client-side code and scale automatically.

To start storing and syncing your data, simply sign up for an account to create your first Firebase. Next, try our 5-minute chat tutorial for a quick demonstration of how Firebase works. Then check out other example apps and dive into the docs.

Integrating Firebase with Node

While you can write entire Firebase applications without any backend code, we provide a full-featured Node.js module to help you run your own servers. To get started, install Firebase via npm:

npm install firebase

Now, just require the library in your application and start storing your data:

var Firebase = require('firebase');
var myRootRef = new Firebase('https://myprojectname.firebaseIO-demo.com/');
myRootRef.set("hello world!");

All data in Firebase can be referenced by a URL. To read and write data to your Firebase, create a reference to the root of your Firebase. You can see all of your data change in Forge, our graphical debugger. Access forge by navigating to the URL of your Firebase.

Writing and Reading Data with Firebase

Writing Data

The basic Firebase write operation is a “set”, which overwrites any data at the specified location. The example below demonstrates setting the first and last names of user ‘fred’.

// First we get a reference to the location of the user’s name data:
var nameRef = new Firebase('https://SampleChat.firebaseIO-demo.com/users/fred/name');

// And then we write data to his first and last name locations:
nameRef.child('first').set('Fred');
nameRef.child('last').set('Swanson');

In addition to strings, you can write booleans, numbers, and objects to any Firebase location. When a javascript object is written, the object properties are automatically mapped to Firebase child locations in a nested fashion: “foo.bar” maps to the child “foo/bar”, “foo.bar.baz” maps to the child “foo/bar/baz” and so on. For example, the code below sets the first and last name of user ‘fred’, just as the previous code example did:

nameRef.set({first : 'Fred', last : 'Swanson'});

Reading Data

Because Firebase is a real-time database, data is never read synchronously. Instead, you read data by attaching a callback to a Firebase reference as shown:

var dataRef = new Firebase('https://SampleChat.firebaseIO-demo.com/users/fred/name/first');
dataRef.on('value', function(snapshot) {
  alert('fred’s first name is ' + snapshot.val());
});

In Firebase, all callbacks are asynchronous. They are triggered both for the initial state of your application and again when data changes. Callbacks receive snapshots of data, which is a picture of the data at a particular Firebase location at a single point in time.

There are 5 different event types for which you can attach callbacks:

  1. value: used to read the entire contents of a Firebase location
  2. child_added: used when retrieving a list of items in Firebase. It fires once for each immediate child of data, and continues to trigger whenever new children are added
  3. child_changed: triggered any time a child or one of its descendents changes
  4. child_removed: triggered when an immediate child is removed
  5. child_moved: used when working with Ordered Data

Check out the documentation for a full explanation on how to attach callbacks to each event type.

Authenticating Users

There are two ways to implement a user login system with Firebase.

Custom Login

If you have your own server and like to control your own authentication, or you wish to integrate existing authentication mechanisms with Firebase, you can integrate your authentication with Firebase by generating your own JSON Web Tokens (JWT). We have a Node.js helper library for generating tokens with Node.

Once you have generated a valid JWT, you can use any Firebase reference to authenticate using the auth API.

var dataRef = new Firebase("https://SampleChat.firebaseIO-demo.com/");
// Log me in.
dataRef.auth(AUTH_TOKEN, function(error) {
  if(error) {
    console.log("Login Failed!", error);
  } else {
    console.log("Login Succeeded!");
  }
});

Authenticating on any reference will authenticate that client to the entire Firebase, and Firebase will seamlessly handle authenticating again if its internet connection is ever lost, so you’ll only need to perform the operation once in your app. To change a client’s credentials (for example, when a user logs in to a different account), simply re-authenticate with a new token. Read the documentation on custom token generation for a full explanation on how this works.

Simple Login

Firebase Simple Login is a built-in service that allows you to authenticate users with only client-side code. It supports Facebook, Twitter, GitHub, Persona, and email / password authentication. To get started, simply include the Firebase Simple login library in your app’s <head> tag and follow the sample code in the documentation here.

Firebase @ Node Knockout

For any questions on apps you’re building during the hackathon, email support@firebase.com or tweet @Firebase on Twitter. You should also search our Google Group mailing list to see if a similar question has been asked by our community.

We’re giving away Firebase credit for awesome apps built during Node Knockout! Winners will receive six months of our Bonfire plan, a $900 value. The Bonfire plan entitles users to 750 concurrent connections, 75 GB of data transfer, and 10 GB of data storage.

Start using Firebase before the hackathon by going through our five minute tutorial and signing up for a free Development account.

This post is sponsored by Groupon, a Node Knockout 2013 platinum sponsor.

Groupon recently completed a year-long project to migrate its U.S. web traffic from a monolithic Ruby on Rails application to a new Node.js stack with substantial results.

The entire U.S. web front-end has been a single Rails codebase from its inception. The front-end codebase quickly grew large, which made it difficult to maintain and challenging to ship new features. As a solution to this gigantic monolith, we decided to re-architect the front-end by splitting it into small, independent and more manageable pieces.

At the center of this project, we rebuilt each major section of the website as an independent Node.js application. We also rebuilt the infrastructure to make all the independent apps work together. Interaction Tier (I-Tier) was the result.

Some of the highlights of this great architecture migration include the following:

  • Page loads are significantly faster across the site

  • Our development teams can develop and ship features faster and with fewer dependencies on other teams

  • We can eliminate redundant implementations of the same features in different countries where Groupon is available

This post is the first in a series about how we re-architected the site and the great benefits we’re seeing that will be key to driving Groupon business forward. Read on for the full story.

This post was written by Drywall author Reza Akhavan.

Drywall is a website and user system for Node.js. It includes a suite of functionality that will save you tons of time with your NKO submission this year. I hope you’ve been training, this isn’t a hello world example.

Take Off the Gloves

Drywall packs a serious punch! On the server we’re using Express, Jade, Passport, Mongoose, Async and Emailjs. And on the client we’re using Bootstrap, Backbone.js, Underscore.js, jQuery, Font-Awesome and Moment.js.

Features Include

  • Basic front end web pages.
  • Contact page has form to email.
  • Login system with forgot password and reset password.
  • Signup and Login with Facebook, Twitter and GitHub.
  • Optional email verification during signup flow.
  • User system with seperate account and admin roles.
  • Admin groups with shared permission settings.
  • Administrator level permissions that override group permissions.
  • Global admin quick search component.

Install Instructions

  1. Clone the repo

     $ git clone git@github.com:jedireza/drywall.git && cd drywall
    
  2. Run

     $ npm install
    
  3. Rename /config.example.js to /config.js and set mongodb and email credentials.

  4. Run app via $ ./run.js or $ node run

DB Setup

You need a few records in the database to start using the user system. Run these commands on your mongo database. Obviously you should use your email address.

use drywall; //or your db name
db.admingroups.insert({ _id: 'root', name: 'Root' });
db.admins.insert({ name: {first: 'Root', last: 'Admin', full: 'Root Admin'}, groups: ['root'] });
var rootAdmin = db.admins.findOne();
db.users.save({ username: 'root', isActive: 'yes', email: 'your@email.addy', roles: {admin: rootAdmin._id} });
var rootUser = db.users.findOne();
rootAdmin.user = { id: rootUser._id, name: rootUser.username };
db.admins.save(rootAdmin);

Now just use the reset password feature to set a password.

  • http://localhost:3000/login/forgot/
  • Submit your email address and wait a second.
  • Go check your email and get the reset link.
  • http://localhost:3000/login/reset/:token/
  • Set a new password.

Login. Customize. Enjoy.

Seeing is Believing

Platform Username Password
https://drywall.nodejitsu.com/ root j1ts00t
https://drywall.herokuapp.com/ root h3r00t
https://drywall.onmodulus.net/ root m0dr00t

Note: The live demos have been modified so you cannot change the root user, the root user’s linked Administrator role or the root Admin Group. This was done in order to keep the app ready to test at all times.

Ready for the Next Round!?

How to use Express. This post was written by express author Tj Holowaychuk.

In this short tutorial for Node Knockout we will be creating a small application using the popular Express framework.

Express is a light-weight Sinatra-inspired web development framework. Express provides several great features such as an intuitive view system, robust routing, an executable for generating applications and much more.

Installation

To get started with Express we first have to install it. There are several ways to do so, however the easiest is with npm:

$ npm install express@3.x

First Express Application

To create our first application we could use express(1) to generate an app for us, however an Express app can be a single JavaScript file if we wish, and in our case of a simple “Hello World” app that is exactly what we will do.

The first thing we need to do is require express, and create an app.

var express = require('express'),
    app = express();

Our next task is to set up one or more routes. A route consists of a path (string or regexp), callback function, and HTTP method. Our hello world example calls app.get() which represents the HTTP GET method, with the path “/”, representing our “root” page, followed by the callback function.

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

Next we need set up a server to listen on a given port. Below we call listen(3000) which attempts to create a server and bind it to port 3000. This can be whatever you like, for example listen(80). Note: for Node Knockout, please ensure your production code listens on port 80.

var server = app.listen(3000);
console.log('Express server started on port %s', server.address().port);

We can execute the app simply by executing node(1) against our JavaScript file:

$ node app.js
Express server started on port 3000

Finally to confirm everything is working as expected:

$ curl http://localhost:3000
Hello World

Middleware

Behind the scenes the Connect middleware framework developed by myself (TJ Holowaychuk) and Tim Caswell is utilized to power the Express middleware. For example if we wish to add logging support to our hello world application, we can add the following line below app = express();:

app.use(express.logger());

For more information on middleware usage view the Middleware section of the Express documentation.

Source

Below is all 12 lines of source we used to create our first Express application:

var express = require('express'),
    app = express();

app.use(express.logger());

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

var server = app.listen(3000);
console.log('Express server started on port %s', server.address().port);

Overview
GoInstant handles the realtime and data storage layers for web and mobile apps, so you don’t have to. We have simple APIs for pub/sub messaging, data synchronization, data storage, multi-user management, authentication, and connection management. It’s low latency, secure, and scales for you. We have customizable widgets for UI features like User Lists and Notifications and MVC integrations like GoAngular that synchronize your model across users and devices. Our goal is to make it as easy as powerful to build awesome realtime, multi-user apps.

Last year several of the Node Knockout winning teams combined Node.js with a multi-user experience to create amazing apps like Disasteroids, Hex, Narwhal Knights & Space Bridge.  We hope more teams will do the same this year, but with GoInstant you’ll be able to build the multi-user aspects of your apps even faster!

You can sign up for a free account and see live examples at goinstant.com

Every winner at Node Knockout is going to get a free lifetime Developer account of GoInstant. We’ll be giving out some hoodies too. As well, we’re offering an extra prize to the best app using GoInstant. It’s a free “One of Everything” Tessel (for awesome hardware hacking using JavaScript!) For details on that, you can read the announcement here: http://bit.ly/H4J5qH

Why Node + GoInstant?
We love Node.js at GoInstant, but when you’re talking about building multi-user & collaborative applications rapidly - it’s not out-of-the-box friendly! This is where GoInstant comes into play.  By combining Node.js with GoInstant you don’t have to worry about data storage, synchronization or a number of other issues that inevitably creep up when building collaborative apps.  We handle it all for you!

Creating a multi-user snake game

Read More

How to use npm. This post was written by npm author Isaac Schlueter.

npm is a NodeJS package manager. As its name would imply, you can use it to install node programs. Also, if you use it in development, it makes it easier to specify and link dependencies.

Installing npm

npm now comes with node. So once you install node you’ll generally have npm too.

More advanced ways to get npm can be found in the npm README.

Read More

This is the 1st in series of posts leading up to the 4th annual Node.js Knockout about how to use node.js.

This post covers how to install node and npm on three popular development platforms: Mac, Ubuntu, and Windows.

Instructions for other platforms can be found on the Node Wiki.

The Easy Way

We personally use package managers to make it easier to keep our node installation up to date, so that’s the approach we generally describe below.

However if you want to skip the steps and download pre-built binaries, you can do so at Joyent’s site: download a binary.

Mac

  1. Go to nodejs.org.
  2. Click install, (to download the pkg).
  3. Open the pkg and run through the install process.

That’s it! Check it worked with a simple Hello, World! example.

Ubuntu

On the latest version of Ubuntu, you can simply:

sudo apt-get install nodejs nodejs-dev npm

On earlier versions, you might need to update your repository:

sudo apt-get install python-software-properties
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs nodejs-dev npm

Then, check it worked with a simple Hello, World! example.

Windows

Since Windows package managers are less common, we recommend just downloading the Windows binary.

Other Linux distributions

If you need help installing in other Linux distributions, you can consult Joyent guide for Mint, Elementary OS, Debian, LMDE, openSUSE, SLE, Fedora, RHEL/CentOS/Scientific Linux 6, Arch Linux and more.

Hello, Node.js

Here’s a quick program to make sure everything is up and running correctly.

// hello_node.js
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Node.js\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');

Run the command by typing node hello_node.js in your terminal.

Now, if you navigate to http://127.0.0.1:8124/ in your browser, you should see the message.

Congrats

You’ve installed node.js and npm.