Sunday, October 10, 2010

Node.js, Express and MongoDB on Snow Leopard - Step by Step

So, I started experimenting with a new technology stack recently. Namely:


While there are many good blog posts out there around these various components, installing this particular stack is a swiftly moving target so I thought I would share my most recent experiences. Here's my quick how-to for installing and running these on Mac OS X Snow Leopard.

MongoDB 
(many thanks to Chris K.)

  1. Download and install

curl http://fastdl.mongodb.org/osx/mongodb-osx-x86_64-1.6.3.tgz > mongo.tgz
tar -xzvf mongo.tgz
sudo mv mongodb-osx-x86_64-1.6.3 /usr/local/mongodb
cat << EOF > /usr/local/mongodb-osx-x86_64-1.6.3/mongodb.conf
dbpath = /usr/local/mongodb
logpath = /var/log/mongodb/output.log
bind_ip = 127.0.0.1
EOF
sudo chown -R root:wheel /usr/local/mongodb-osx-x86_64-1.6.3
sudo ln -s /usr/local/mongodb-osx-x86_64-1.6.3 /usr/local/mongodb

  2. Make a launchd job for MongoDB.

Save the following as "/Library/LaunchDaemons/org.mongodb.mongod.plist":


  Label
  org.mongodb.mongod
  ProgramArguments
  
    /usr/local/mongodb/bin/mongod
    run
    --config
    /usr/local/mongodb/mongod.conf
  
  RunAtLoad
  
  KeepAlive
  
  WorkingDirectory
  /usr/local/mongodb
  StandardErrorPath2
  /var/log/mongodb/output.log
  StandardOutPath
  /var/log/mongodb/output.log



Load the launchd job:

sudo launchctl load /Library/LaunchDaemons/org.mongodb.mongod.plist

Pull up http://localhost:28017 in your browser and verify that MongoDB is running

node.js and friends(many thanks to Isaac S.)

  1. Install node.js and npm (node package manager)

echo 'export PATH=$HOME/local/bin:$PATH' >> ~/.bashrc
. ~/.bashrc
mkdir ~/local
mkdir ~/node-latest-install
cd ~/node-latest-install
curl http://nodejs.org/dist/node-latest.tar.gz | tar xz --strip-components=1
./configure --prefix=~/local
make install
curl http://npmjs.org/install.sh | sh

  2. Install Express, Jade and Mongoose

npm install express
npm install jade
npm install mongoose

Putting it all together(many thanks to Éber D.)

cd ~/path/to/my/project
mkdir views
mkdir models

  1. Create the following files:

./app.js

var sys      = require('sys'),
    express  = require('express'),
    app      = express.createServer(),
    Counter  = require('./models/counter');

app.configure(function(){
  app.use(express.methodOverride());
  app.use(express.bodyDecoder());
  app.use(app.router);
  app.use(express.staticProvider(__dirname + '/public'));
  app.set('view engine', 'jade');
});

app.get('/', function(req, res) {
  Counter.count(function(num_records) {
    if (num_records > 0) {
      var c = new Counter();
      c.num = 0;
      c.save(function(){
        res.render('index', {locals: {count: c.num}});
      });
    } else {
      Counter.find().last(function(c){
        c.num = c.num + 1;
        c.save(function(){
          res.render('index', {locals: {count: c.num}});
        });
      });
    }
  });  
});

app.listen(3000);
sys.puts("HTTP server is listening on port 3000");

./models/counter.js

var mongoose = require('mongoose').Mongoose,
    db       = mongoose.connect('mongodb://localhost/db');

mongoose.model('Counter', {
  properties: ['num']
});

module.exports = db.model('Counter');

./views/layout.jade

!!! 5
html(lang="en")
  head
    title= "My Test App"
    :javascript
      | if (foo) {
      |    bar()
      | }
  body
    div!= body

./views/index.jade

h1 My Test App
#container
  p This page has been viewed #{count} times

  2. Start your node server

node app.js

  3. Bask in the glory of your success by visiting http://localhost:3000

If all went well, you'll see a welcome message and a counter of the number of times the page has been viewed. Happy coding!

1 comment:

Goran said...

First off, tanks for the step-by-step. I did discover discrepancies with the directory references within the mongodb instructions.

Take into consideration the move/renaming of the 'mongodb-osx-x86_64-1.6.3' directory:

sudo mv mongodb-osx-x86_64-1.6.3 /usr/local/mongodb

The name of the directory is now ''mongodb'...

Then, in the steps thereafter, references are made to the 'mongodb-osx-x86_64-1.6.3' directory. Bottom line, all instances of 'mongodb-osx-x86_64-1.6.3' need to be changed to simply 'mongodb'.