Starting out with Node.js

Here is an excellent guide for starting out with Node.js, the Express framework, and MongoDB: click me.

So what more is there for me to add? Well, here is some of my code and folder structure so you have a better idea of how to generalize this for web development.

Here are some differences that I introduce:

  • The article above uses an outdated method of connecting to MongoDB, so mine shows you a different way using the MongoClient class.
  • The example in the article above shows you a quick way to create REST services. You may also want to serve normal web pages, so that’s included below using the Express framework
  • I also include a way to exit the server gracefully (ie. a hook to release resources).

So here is a snapshot of my folder structure so you know what to aim for:

Screen Shot 2014-02-21 at 2.23.50 PM

Here’s the content of server.js (note the serving of normal web pages):

var port=3000;
var express = require('express');
var hand = require('./routes/hand');

var app = express();

/*********************************
 * Serve all pages under /html
 *********************************/
app.use(express.static(__dirname+'/html'));

/*************************
 * Route REST calls
 ************************/
app.get('/hand/:id', hand.getHandById);

/*************************
 * Start Server
 ************************/
app.listen(port);
console.log('Listening on port '+port);

Here’s the content of my hand.js

var mongo = require('mongodb');

var DB_NAME = 'myMongoDb';

var MongoClient = mongo.MongoClient;
var Server = mongo.Server;
var BSON = mongo.BSONPure;
var mongoClient = null;

/******************
 * Ensure proper shutdown when exiting
 ******************/
process.on('SIGINT', function() { process.exit(); });
process.on('exit', function shutdown() {
	console.log("shutting down...");
	if( mongoClient ) {
		console.log("close mongo");
		mongoClient.close();
	}
});

/*******************
 * Mongo Setup
 *******************/
mongoClient = new MongoClient(new Server('localhost', 27017, {auto_reconnect: true}));
mongoClient.open(function(err, mongoClient) {
	if( err ) {
		console.log(err);
		process.exit(1);
	}
});

var db = mongoClient.db(DB_NAME);
var handCollection = db.collection('hand');

/*******************
 * REST API
 *******************/
exports.getHandById = function(req, res) {
	var id = new BSON.ObjectID(req.params.id);
	handCollection.findOne({'_id':id}, function(err, item) {
		console.log('getHandById{'+id+'}');
		res.send(item);
	});
};

Advertisements
Tagged , ,

7 thoughts on “Starting out with Node.js

  1. Hello! I just wanted to ask if you ever have any trouble with hackers?
    My last blog (wordpress) was hacked and I ended up losing months of hard work
    due to no backup. Do you have any methods to stop hackers?

    • kanesee says:

      I’ve been lucky that I haven’t had any hacks (that I’m aware of).
      But I found out my company’s wordpress site was hacked. It was fairly benign in that they simply injected some hidden spam links to increase traffic to their sites.
      Make sure you don’t have any default accounts and default passwords around. Not sure what else I can say.

  2. Admiring the hard work you put into your website and in depth information you present.
    It’s good to come across a blog every once in a while that isn’t the same old rehashed material.
    Great read! I’ve bookmarked your site and I’m adding your RSS feeds to my Google account.

  3. Hello there! I just would like to offer you a huge thumbs
    up for the excellent info you have got right here on this post.
    I will be returning to your site for more soon.

  4. Jay says:

    It’s awesome in favor of me to have a web site, which is beneficial designed for my knowledge.
    thanks admin Jay

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: