<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>The Holmes Office</title>
	<atom:link href="http://theholmesoffice.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://theholmesoffice.com</link>
	<description>Where Simon Holmes frees some brain space</description>
	<lastBuildDate>Mon, 11 Mar 2013 00:15:27 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Node.js, Express and Mongoose</title>
		<link>http://theholmesoffice.com/node-js-express-and-mongoose/</link>
		<comments>http://theholmesoffice.com/node-js-express-and-mongoose/#comments</comments>
		<pubDate>Fri, 01 Feb 2013 09:43:01 +0000</pubDate>
		<dc:creator>Simon Holmes</dc:creator>
				<category><![CDATA[Knowing Node]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[mongoose]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[nodejs]]></category>

		<guid isPermaLink="false">http://theholmesoffice.com/?p=628</guid>
		<description><![CDATA[Building on previous tutorials, this one brings together Node.js, Express, MongoDB and Mongoose. Here you will see how to create a reusable persistent connection and use Mongoose to retrieve MongoDB data, and Express to output it to screen.]]></description>
				<content:encoded><![CDATA[<p>Previously we have used <a title="Mongoose and Node.js tutorial" href="http://theholmesoffice.com/mongoose-and-node-js-tutorial/">Node.js with Mongoose</a>, and <a title="Introducing the Express.js framework for node.js" href="http://theholmesoffice.com/express-js-framework-node-js/">Express with hard coded data</a>. Now it is time to bring it all together using <strong>Node.js, Express, MongoDB </strong>and<strong> Mongoose</strong>.</p>
<h2>Start with the Express project</h2>
<p>I created a new copy of the Express project from the previous tutorial, source of which you can <a title="Knowing Node 'testpage-express' folder on GitHub" href="https://github.com/simonholmes/knowing-node/tree/master/testpage-express" target="_blank">find on GitHub</a>.</p>
<p>This has got our simple route and single page of info, but the data list for the teams is hard-coded as a JSON object in the &#8216;routes/index.js&#8217; file.</p>
<h2>Install Connect and Mongoose</h2>
<p>The easiest way to do this is to use the package.json file in the root of the project and npm. This method allows you to install all of the modules you need at once, or you can add some in later, like we are doing now. This is a useful habit to get in to.</p>
<p>Opening up the package.json file you should see something like this:</p>
<pre class="brush: jscript; title: ; notranslate">
{
 &quot;name&quot;: &quot;application-name&quot;,
 &quot;version&quot;: &quot;0.0.1&quot;,
 &quot;private&quot;: true,
 &quot;scripts&quot;: {
  &quot;start&quot;: &quot;node app&quot;
 },
 &quot;dependencies&quot;: {
  &quot;express&quot;: &quot;3.0.0rc5&quot;,
  &quot;jade&quot;: &quot;*&quot;
 }
}
</pre>
<p>We are going to add a couple of lines to the &#8216;dependencies&#8217; section to include Connect and Mongoose, so that it now looks like this:</p>
<pre class="brush: jscript; title: ; notranslate">
{
 &quot;name&quot;: &quot;application-name&quot;,
 &quot;version&quot;: &quot;0.0.1&quot;,
 &quot;private&quot;: true,
 &quot;scripts&quot;: {
  &quot;start&quot;: &quot;node app&quot;
 },
 &quot;dependencies&quot;: {
  &quot;express&quot;: &quot;3.0.0rc5&quot;,
  &quot;jade&quot;: &quot;*&quot;,
  &quot;connect&quot;: &quot;*&quot;,
  &quot;mongoose&quot;: &quot;*&quot;
 }
}
</pre>
<p>Save this file and open a terminal prompt at the project folder and run:</p>
<pre class="brush: bash; title: ; notranslate">npm install</pre>
<p>This will read the dependency list from the package.json file and install any new packages into the project.</p>
<h2>Setting up the Mongoose connection and defining the data model</h2>
<p>In the root directory of the application we&#8217;ll create a &#8216;model&#8217; folder to contain our database connection, schema information and any interactions with it.</p>
<p>In this folder we will start off by creating a file db.js with the following content:</p>
<pre class="brush: jscript; title: ; notranslate">

var mongoose = require( 'mongoose' );

var teamSchema = new mongoose.Schema({
 country: String,
 GroupName: String
});
mongoose.model( 'Team', teamSchema );

mongoose.connect( 'mongodb://localhost/euro2012' );

</pre>
<p>Here we are doing four things:</p>
<ol>
<li>&#8220;Requiring&#8221; Mongoose so that we can use it</li>
<li>Defining the schema for a team</li>
<li>Building a &#8216;model&#8217; of this schema, called &#8220;Team&#8221;</li>
<li>Connecting to the database, in this case a MongoDB database called &#8216;euro2012&#8242; on the &#8216;localhost&#8217; server</li>
</ol>
<p>The schema and model should both be familiar if you&#8217;ve seen my <a title="Mongoose and Node.js tutorial" href="http://theholmesoffice.com/mongoose-and-node-js-tutorial/">Mongoose &amp; Node.js tutorial</a>.</p>
<h2><strong>Getting data from the database</strong></h2>
<p>In the <em>&#8216;model&#8217;</em> folder create a file teams.js. We will use this to search the database for teams with a given &#8216;GroupName&#8217; and return a JSON response. If you had other &#8216;team&#8217; related queries they could be placed in here &#8211; e.g. all data about a given team.</p>
<p>Our file will need an export function that:</p>
<ol>
<li>Takes a &#8216;GroupName&#8217; value as a parameter</li>
<li>Takes a callback function as a second parameter</li>
<li>Searches the MongoDB database for teams with the provided &#8216;GroupName&#8217;</li>
<li>Send the database output to the callback function.</li>
</ol>
<p>We created a &#8220;Team.find()&#8221; function last time round, so by taking that, bringing in the &#8216;Team&#8217; model as a local variable and  requiring Mongoose, <em>teams.js</em> should look something like this:</p>
<pre class="brush: jscript; title: ; notranslate">

var mongoose = require('mongoose');

exports.teamlist = function teamlist(gname,callback){
 var Team = mongoose.model( 'Team' );
 Team.find({'GroupName':gname}, function (err, teams) {
  if(err){
   console.log(err);
  }else{
   console.log(teams);
   callback(&quot;&quot;,teams);
  }
 })// end Team.find
}// end exports.teamlist

</pre>
<h2>Establish the Mongoose connection</h2>
<p>Mongoose is designed to have a reusable connection created on application startup. It also makes sense to only define the schemas once. So as we start our app by calling app.js this is where we need to require db.js. Let&#8217;s add it in to the require section at the top of the file, just after requiring Express.</p>
<pre class="brush: jscript; title: ; notranslate">

var express = require('express')
 , db = require('./model/db')
 , routes = require('./routes')
 , http = require('http')
 , path = require('path');

</pre>
<p>(Snipped for brevity, keep the rest of the app.js file intact).</p>
<h2><strong>Displaying the data on the webpage</strong></h2>
<p>When we created the static data version in Express we hardcoded the JSON object into routes/index like so:</p>
<pre class="brush: jscript; title: ; notranslate">

exports.index = function(req, res){
 var strGroup = &quot;D&quot;;
 res.render('index', {
  title: 'Test web page on node.js using Express',
  pagetitle: 'Hello there',
  group: strGroup,
  teams: [{&quot;country&quot;:&quot;England&quot;},{&quot;country&quot;:&quot;France&quot;},{&quot;country&quot;:&quot;Sweden&quot;},{&quot;country&quot;:&quot;Ukraine&quot;}]
 });
};

</pre>
<p>Replacing this with the MongoDB data via Mongoose is surprisingly easy. We need to:</p>
<ol>
<li>Require the <em>teams.js </em>model file</li>
<li>Call the &#8216;teamlist&#8217; export function, sending it:
<ol>
<li>The &#8216;GroupName&#8217; of teams we are searching for</li>
<li>The res.render functions as a callback build the page &#8211; including the list of teams &#8211; when the database query completes</li>
</ol>
</li>
</ol>
<p>So let&#8217;s modify routes/index.js like so:</p>
<pre class="brush: jscript; title: ; notranslate">

var teamdata = require('../model/teams');

exports.index = function(req, res){
 var strGroup = &quot;D&quot;;
 teamdata.teamlist(strGroup,function(err,teamlist){
  res.render('index', {
   title: 'Test web page on node.js using Express and Mongoose',
   pagetitle: 'Hello there',
   group: strGroup,
   teams: teamlist
  });
 });
};

</pre>
<p>Again, this is very similar code to that used in my earlier Mongoose tutorial, but here the Express res.render() function is a much neater way of building the resulting web page.</p>
<h2>See it working</h2>
<p>In terminal cd into the root folder for this site and run it by typing</p>
<pre class="brush: bash; title: ; notranslate">node app</pre>
<p>Head over to localhost:3000 in your browser and you should see something like this:</p>
<p><img class="alignnone size-medium wp-image-641" alt="Testing Mongoose and Express" src="http://theholmesoffice.com/wp-content/uploads/2013/02/Screenshot-from-2013-02-01-003549-300x208.png" width="300" height="208" /></p>
<p>If you&#8217;ve kept the console.log statements in the code, you should see verification of the data being retrieved from the database. Similar to this:</p>
<p><img class="alignnone size-medium wp-image-642" alt="Mongoose confirmation in terminal" src="http://theholmesoffice.com/wp-content/uploads/2013/02/Screenshot-from-2013-02-01-003532-300x137.png" width="300" height="137" /></p>
<p>So there it is. Mongoose and Express together, greatly simplifying some of the tasks of development in Node.js</p>
<div id='Knowing_Node_GitHub' class='widgets_on_page'>
    <ul><li id="text-4" class="widget widget_text">			<div class="textwidget"><blockquote><p><strong>Get the source code</strong></p>
<p>The source code for this and my other tutorials on Node.js is available on GitHub here:&nbsp;<a title="Knowing Node source code on GitHub" href="https://github.com/simonholmes/knowing-node/" target="_blank">https://github.com/simonholmes/knowing-node/</a></p></blockquote></div>
		</li></ul>
  </div><!-- widgets_on_page -->
<p>Now that we have the building blocks of Node.js, Express, MongoDB and Mongoose in place, next time we&#8217;ll start building a web app we can actually use in the real world.</p>
<div id='Knowing_Node_book' class='widgets_on_page'>
    <ul><li id="text-3" class="widget widget_text">			<div class="textwidget"><p><a href="http://www.knowingnode.com/?utm_source=theholmesoffice&utm_medium=blog&utm_content=post-foot&utm_campaign=tho_blog" target="_blank" title="Visit knowingnode.com (opens in a new window)"><img src="http://theholmesoffice.com/wp-content/uploads/2013/03/KnowingNodeBookBanner.png" width="500" height="131" alt="Find this useful? Check out my book, Knowing Node" /></a></p></blockquote></div>
		</li></ul>
  </div><!-- widgets_on_page -->
]]></content:encoded>
			<wfw:commentRss>http://theholmesoffice.com/node-js-express-and-mongoose/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introducing the Express.js framework for node.js</title>
		<link>http://theholmesoffice.com/express-js-framework-node-js/</link>
		<comments>http://theholmesoffice.com/express-js-framework-node-js/#comments</comments>
		<pubDate>Thu, 17 Jan 2013 22:58:39 +0000</pubDate>
		<dc:creator>Simon Holmes</dc:creator>
				<category><![CDATA[Knowing Node]]></category>
		<category><![CDATA[express]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[nodejs]]></category>

		<guid isPermaLink="false">http://theholmesoffice.com/?p=601</guid>
		<description><![CDATA[An introduction to Express, a web application framework for node.js. This tutorial covers installing Express globally, creating a template project, installing the dependencies and viewing the results in the browser.]]></description>
				<content:encoded><![CDATA[<p>Up to this point in the <a title="Knowing Node - node.js tutorials" href="http://theholmesoffice.com/category/knowing-node/">Knowing Node series</a> we have used node.js to create a server, built a rudimentary MVC framework, and served a webpage pulling data from a MongoDB database. We used Mongoose to make working with the database easier, and now we&#8217;re going to look at a way of making the basic server and framework setup easier. Say hello to <a title="Visit Express JS (opens in a new window)" href="http://expressjs.com/" target="_blank">Express</a>!</p>
<h2>What is Express?</h2>
<p>Express is a popular web application framework for node. The first thing you&#8217;ll enjoy is that it simplifies the web server setup &#8211; including routing for static files &#8211; and creates a directory structure as a start point for organising your  code.</p>
<p>We&#8217;re going to use it as we&#8217;re looking at building a web application, whether that&#8217;s a one page app or a multipage site isn&#8217;t important right now.</p>
<h2>Installing Express</h2>
<p>First of all we need to install Express globally. So in terminal:</p>
<pre class="brush: bash; title: ; notranslate">sudo npm install -g express</pre>
<h2>Creating a project</h2>
<p>Now that we&#8217;ve got Express installed globally, we let&#8217;s use it to create a new project. Here&#8217;s we create a new folder for our Express project, and install Express and it&#8217;s dependencies.</p>
<pre class="brush: bash; title: ; notranslate">mkdir testpage-express
cd testpage-express
express #this installs an instance of express into the directory using the default options
npm install #this installs the dependcies</pre>
<p>You can override some of the default install options when creating a new project, for example to specify a different HTML templating engine or CSS compiler.</p>
<p>See the <a title="Express.js install options" href="http://expressjs.com/guide.html#executable" target="_blank">official Excpress.js guide</a> for more info.</p>
<h2>Start the project and view it in a browser</h2>
<p>In terminal:</p>
<pre class="brush: bash; title: ; notranslate">node app</pre>
<p>This should display a confirmation in terminal &#8220;Express server listening on port 3000&#8243;. 3000 is the default port used by Express, so head over to localhost:3000 in your browser and you should see something like this:</p>
<p><img class="alignnone  wp-image-608" alt="Default Express js site on node.js" src="http://theholmesoffice.com/wp-content/uploads/2013/01/Screenshot-from-2013-01-16-224601.png" width="599" height="320" /></p>
<p>Nice. That was pretty easy right?</p>
<p>If you look at the page you may notice that it&#8217;s not using the default browser font, meaning there must be a stylesheet included.</p>
<p>Take a look back into the terminal that you use to start the process and you should see confirmation that it has delivered the URL &#8216;/&#8217; and the stylesheet &#8216;/stylesheets/style.css&#8217;.<br />
<img class="alignnone size-full wp-image-612" alt="Terminal window confirming Express.js routes" src="http://theholmesoffice.com/wp-content/uploads/2013/01/Screenshot-from-2013-01-17-222459.png" width="526" height="157" /></p>
<p>So there we go, a few terminal commands and you&#8217;ve got a node.js webserver and framework in place. More excitingly we&#8217;ve got that basis for a web-app just waiting for us!</p>
<p>Next time we&#8217;ll take a look under the hood and build our simple site in Express, using the built in routing and template engines.</p>
<blockquote><p><strong>Get the source code</strong></p>
<p>The source code for this and my other tutorials on Node.js is available on GitHub here: <a title="Knowing Node source code on GitHub" href="https://github.com/simonholmes/knowing-node/" target="_blank">https://github.com/simonholmes/knowing-node/</a></p></blockquote>
<div id='Knowing_Node_book' class='widgets_on_page'>
    <ul><li id="text-3" class="widget widget_text">			<div class="textwidget"><p><a href="http://www.knowingnode.com/?utm_source=theholmesoffice&utm_medium=blog&utm_content=post-foot&utm_campaign=tho_blog" target="_blank" title="Visit knowingnode.com (opens in a new window)"><img src="http://theholmesoffice.com/wp-content/uploads/2013/03/KnowingNodeBookBanner.png" width="500" height="131" alt="Find this useful? Check out my book, Knowing Node" /></a></p></blockquote></div>
		</li></ul>
  </div><!-- widgets_on_page -->
]]></content:encoded>
			<wfw:commentRss>http://theholmesoffice.com/express-js-framework-node-js/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Knowing Node source code files on GitHub</title>
		<link>http://theholmesoffice.com/knowing-node-source-code-files-on-github/</link>
		<comments>http://theholmesoffice.com/knowing-node-source-code-files-on-github/#comments</comments>
		<pubDate>Mon, 12 Nov 2012 22:33:39 +0000</pubDate>
		<dc:creator>Simon Holmes</dc:creator>
				<category><![CDATA[Knowing Node]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[nodejs]]></category>

		<guid isPermaLink="false">http://theholmesoffice.com/?p=592</guid>
		<description><![CDATA[All of the source files for my Knowing Node series of tutorials on Node.js are now available on GitHub.]]></description>
				<content:encoded><![CDATA[<p>All of the source files for my Knowing Node series of tutorials on Node.js are now available on GitHub.</p>
<p>You get can get them here: <a title="Knowing Node source files on GitHub" href="https://github.com/simonholmes/knowing-node/" target="_blank">https://github.com/simonholmes/knowing-node/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://theholmesoffice.com/knowing-node-source-code-files-on-github/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mongoose and Node.js tutorial</title>
		<link>http://theholmesoffice.com/mongoose-and-node-js-tutorial/</link>
		<comments>http://theholmesoffice.com/mongoose-and-node-js-tutorial/#comments</comments>
		<pubDate>Wed, 31 Oct 2012 07:34:23 +0000</pubDate>
		<dc:creator>Simon Holmes</dc:creator>
				<category><![CDATA[Knowing Node]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[mongoose]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[nodejs]]></category>

		<guid isPermaLink="false">http://theholmesoffice.com/?p=578</guid>
		<description><![CDATA[How to use Mongoose with Node.js and MongoDB. Based on the code of a previous example using the native drivers, this tutorial shows how to install Mongoose for Node.js, introduces the basic concepts, and converts the MongoDB Native Driver code into Mongoose code.]]></description>
				<content:encoded><![CDATA[<p>The aim of this tutorial is to take away some of the hassle when using MongoDB with Node.js. Last time out we used the <a title="How to get data from MongoDB into Node.js" href="http://theholmesoffice.com/how-to-ge-data-from-mongodb-into-node-js/">Node.js native MongoDB driver to get data out of a MongoDB database</a>. This worked well, and retrieved our data. But it did seem like an awful lot of code and callbacks for such a simple operation.</p>
<p>Here&#8217;s an easier way.</p>
<h2>Introducing Mongoose!</h2>
<p>In their own words <a title="Mongoose.js" href="http://mongoosejs.com/" target="_blank">Mongoose</a> provides &#8211; &#8220;elegant mongodb object modeling for node.js&#8221; and &#8220;solves common problems for real-world applications&#8221;. Essentially, for our purposes here, it exposes only what you need to see and does everything else behind the scenes.</p>
<h3>Installing Mongoose</h3>
<p>First things first, you&#8217;ll need to install Mongoose (assuming you already have Node.js, npm and MongoDB installed).</p>
<p>cd into the root directory of your site &#8211; I&#8217;ve made a copy of my &#8220;testpage-site&#8221; folder called &#8220;testpage-mongoose&#8221; &#8211; and enter:</p>
<pre class="brush: bash; title: ; notranslate">sudo npm install mongoose</pre>
<p>Now we&#8217;re ready to go!</p>
<p>Taking our code from last time as a start point, we are going to need to look at our controller file, and our model file.</p>
<h3>Changing the model file</h3>
<p>Most of our work here will be in the &#8216;model&#8217; file, as we are dealing directly with the database, so let&#8217;s start there. For this I have created a new file &#8216;mongoose-data.js&#8217; using &#8216;mongo-data.js&#8217; from the <a title="How to get data from MongoDB into Node.js" href="http://theholmesoffice.com/how-to-ge-data-from-mongodb-into-node-js/">previous tutorial</a> as a template.</p>
<h2>Connecting to MongoDB using Mongoose</h2>
<p>This will be where Mongoose is going to manage the connection to our MongoDB database, so let&#8217;s start off with this code snippet:</p>
<pre class="brush: bash; title: ; notranslate">
var mongoose = require('mongoose'),
 db = mongoose.createConnection('localhost', 'euro2012');
db.on('error', console.error.bind(console, 'connection error:'));
</pre>
<p>Note that we now <em>require</em> &#8216;mongoose&#8217; instead of &#8216;mongodb&#8217;. We have also very easily created a connection to our database &#8216;euro2012&#8242; on the server &#8216;localhost&#8217;. Finally, we have created a default error handler to catch any connection errors.</p>
<blockquote><p><strong>A note on connecting and disconnecting</strong></p>
<p>As Aaron Heckmann has pointed out in the comments &#8211; and <a href="http://geekli.st/aaronheckmann" target="_blank">he knows what</a> <a href="https://github.com/aheckmann" target="_blank">he&#8217;s talking about</a> &#8211; it is &#8220; best to open your db connection once, at application startup, and leave it open until your app shuts down&#8221;.</p></blockquote>
<h2>Using Node.js and Mongoose to query MongoDB</h2>
<p>Let&#8217;s dive straight into the meat of the code and see what is happening in our &#8216;export&#8217; function. The export function itself expects two parameters, a variable &#8216;gname&#8217; that we will search for in the database, and a callback function that we&#8217;ll execute when the database query is complete.</p>
<pre class="brush: bash; title: ; notranslate">
exports.teamlist = function(gname,callback){
 db.once('open', function(){
  var teamSchema = new mongoose.Schema({
   country: String,
   GroupName: String
  });
  var Team = db.model('Team', teamSchema);
  Team.find({'GroupName':gname}, function (err, teams) {
   if(err){
    onErr(err,callback);
   }else{
    mongoose.connection.close();
    console.log(teams);
    callback(&quot;&quot;,teams);
   }
  })// end Team.find
 });// end db.once open
};
</pre>
<p>First, we open the database in the <strong>db.once</strong> wrapper, and send the rest of the code through as a callback to be executed once the database connection is open.</p>
<h3>Setting a schema and building a model</h3>
<p>Mongoose requires a schema to be set for the data. This enables Mongoose to then build a model framework for the information we will be dealing with. Ours is pretty simple here, using just a couple of strings &#8211; see the <a title="Schemas in Mongoose" href="http://mongoosejs.com/docs/guide.html" target="_blank">Mongoose docs</a> for more info on schemas.</p>
<p>Here&#8217;s our schema:</p>
<pre class="brush: bash; title: ; notranslate">
var teamSchema = new mongoose.Schema({
 country: String,
 GroupName: String
});
</pre>
<p>And here&#8217;s the simple one liner to build a model &#8216;Team&#8217; from the schema:</p>
<pre class="brush: bash; title: ; notranslate">var Team = db.model('Team', teamSchema)</pre>
<h3>Using Mongoose &#8220;find&#8221; to query MongoDB</h3>
<p>The &#8220;find&#8221; method of Mongoose is very similar to that of the native driver, and is happy to accept the same filter object as an argument. You simply apply the find method to the model you&#8217;ve just created, sending the filter object/search query as the first parameter, and a callback function as the second. This callback function has two possible parameters, an error object and the returned data following the query.</p>
<pre class="brush: bash; title: ; notranslate">
Team.find({'GroupName':gname}, function (err, teams) {
 if(err){
  onErr(err,callback);
 }else{
  mongoose.connection.close();
  console.log(teams);
  callback(&quot;&quot;,teams);
 }
})// end Team.find</pre>
<p>The Mongoose &#8216;find&#8217; method automatically returns an array of JSON objects, reducing the amount of coding effort you have to go to in order to make the data more usable. Our console.log from the above snippet returns something along the lines of:</p>
<pre class="brush: jscript; gutter: false; title: ; notranslate">
[ { _id: 50011ff173ca2c992a7bae46,
 country: 'England',
 GroupName: 'D' },
 { _id: 500122cb73ca2c992a7bae48,
 country: 'France',
 GroupName: 'D' },
 { _id: 5001230673ca2c992a7bae49,
 country: 'Sweden',
 GroupName: 'D' },
 { _id: 5001231073ca2c992a7bae4a,
 country: 'Ukraine',
 GroupName: 'D' } ]
</pre>
<p>Once we have the data we send it through to the callback function provided when the exports function was called.</p>
<h4>Catching errors</h4>
<p>The last part of our model file deals with catching and returning errors. You can see that if there is an error with the find operation we call this function onErr(err,callback).</p>
<pre class="brush: jscript; title: ; notranslate">
var onErr = function(err,callback){
 mongoose.connection.close();
 callback(err);
};
</pre>
<p>This simply closes the database connection and then sends the error object back to the original callback function.</p>
<h2>Using the data in the web page</h2>
<p>To get the returned JSON data into our website we need to set up the controller. I have set up a new copy of the controllers/home-mongo.js file and called it home-mongoose.js.</p>
<p>Here is the full source code for that file:</p>
<pre class="brush: jscript; title: ; notranslate">

var template = require('../views/template-main');
var mongo_data = require('../model/mongoose-data');

exports.get = function(req, res) {
 var strGroup = &quot;D&quot;;
 mongo_data.teamlist(strGroup,function(err,teamlist){
  if(!err){
   var strTeam = &quot;&quot;, i = 0, teamCount = teamlist.length;
   for (i = 0; i&lt;teamCount;) {
    strTeam = strTeam + &quot;&lt;li&gt;&quot; + teamlist[i].country + &quot;&lt;/li&gt;&quot;;
    i = i+1;
   }
   strTeam = &quot;&lt;ul&gt;&quot; + strTeam + &quot;&lt;/ul&gt;&quot;
   res.writeHead(200, {'Content-Type': 'text/html'});
   res.write(
    template.build(&quot;Test web page on node.js&quot;,&quot;Hello there&quot;,&quot;&lt;p&gt;The teams in Group &quot; + strGroup + &quot; for Euro 2012 are:&lt;/p&gt;&quot; + strTeam));
   res.end();
  }
  else{
   res.writeHead(200, {'Content-Type': 'text/html'});
   res.write(
    template.build(&quot;Oh dear&quot;,&quot;Database error&quot;,&quot;&lt;p&gt;Error details: &quot; + err + &quot;&lt;/p&gt;&quot;));
   res.end();
  }
 });
};

</pre>
<p>First of all, we need to require the new model file.</p>
<p>Secondly, we have changed the way the main &#8216;get&#8217; function works very slightly by providing the name of the group of teams we want. In this case &#8220;D&#8221;. This means that we will search the database for this and return the relevant teams (this is what we did in the model at the start of this post).</p>
<p>After that, looping through the list and sending the output to the template is pretty much the same as before.</p>
<h2>That&#8217;s it!</h2>
<p>Well, that&#8217;s nearly it. Don&#8217;t forget to change the router to require the &#8216;home-mongoose&#8217; controller instead of &#8216;home-mongo&#8217;.</p>
<p>Now we have Mongoose acting as an interface to our MongoDB database, taking much of the coding pain away and simplifying the process.</p>
<blockquote><p><strong>Get the source code</strong></p>
<p>The source code for this and my other tutorials on Node.js is available on GitHub here: <a title="Knowing Node source code on GitHub" href="https://github.com/simonholmes/knowing-node/" target="_blank">https://github.com/simonholmes/knowing-node/</a></p></blockquote>
<div id='Knowing_Node_book' class='widgets_on_page'>
    <ul><li id="text-3" class="widget widget_text">			<div class="textwidget"><p><a href="http://www.knowingnode.com/?utm_source=theholmesoffice&utm_medium=blog&utm_content=post-foot&utm_campaign=tho_blog" target="_blank" title="Visit knowingnode.com (opens in a new window)"><img src="http://theholmesoffice.com/wp-content/uploads/2013/03/KnowingNodeBookBanner.png" width="500" height="131" alt="Find this useful? Check out my book, Knowing Node" /></a></p></blockquote></div>
		</li></ul>
  </div><!-- widgets_on_page -->
]]></content:encoded>
			<wfw:commentRss>http://theholmesoffice.com/mongoose-and-node-js-tutorial/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Node.js fundamentals: how to upgrade the Node.js version</title>
		<link>http://theholmesoffice.com/node-js-fundamentals-how-to-upgrade-the-node-js-version/</link>
		<comments>http://theholmesoffice.com/node-js-fundamentals-how-to-upgrade-the-node-js-version/#comments</comments>
		<pubDate>Wed, 10 Oct 2012 07:00:08 +0000</pubDate>
		<dc:creator>Simon Holmes</dc:creator>
				<category><![CDATA[Knowing Node]]></category>
		<category><![CDATA[node fundamentals]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[version managemnt]]></category>

		<guid isPermaLink="false">http://theholmesoffice.com/?p=572</guid>
		<description><![CDATA[A quick tutorial showing you how to upgrade the version of Node.js running on your machine.]]></description>
				<content:encoded><![CDATA[<p>Node.js is being actively developed, and the latest stable version frequently changes. From time to time you will find a module that doesn&#8217;t work with your current version of Node and says that you need to upgrade.</p>
<p>Fortunately there is a very easy way of managing your node version, using the <a title="'n' - node.js binary manager" href="https://github.com/visionmedia/n" target="_blank">Node binary manager module &#8216;n&#8217;</a>.</p>
<p>1: Check your current version of Node.</p>
<pre class="brush: bash; title: ; notranslate">$node -v
v0.6.12</pre>
<p>2: Clear your npm cache</p>
<pre class="brush: bash; title: ; notranslate">sudo npm cache clean -f</pre>
<p>3: Install &#8216;n&#8217;</p>
<pre class="brush: bash; title: ; notranslate">sudo npm install -g n</pre>
<p>4: Upgrade to a later version (this step can take a while) You can specify a particular version like so:</p>
<pre class="brush: bash; title: ; notranslate">sudo n 0.8.11</pre>
<p>Or you can just tell the manager to install the latest stable version like so:</p>
<pre class="brush: bash; title: ; notranslate">sudo n stable</pre>
<p>5: Check the running version of Node to verify that it has worked:</p>
<pre class="brush: bash; title: ; notranslate">$node -v
v0.8.11</pre>
<p><em>If the version doesn&#8217;t number output in step 5 isn&#8217;t what you were expecting, you may need to reboot.</em></p>
<div id='Knowing_Node_book' class='widgets_on_page'>
    <ul><li id="text-3" class="widget widget_text">			<div class="textwidget"><p><a href="http://www.knowingnode.com/?utm_source=theholmesoffice&utm_medium=blog&utm_content=post-foot&utm_campaign=tho_blog" target="_blank" title="Visit knowingnode.com (opens in a new window)"><img src="http://theholmesoffice.com/wp-content/uploads/2013/03/KnowingNodeBookBanner.png" width="500" height="131" alt="Find this useful? Check out my book, Knowing Node" /></a></p></blockquote></div>
		</li></ul>
  </div><!-- widgets_on_page -->
]]></content:encoded>
			<wfw:commentRss>http://theholmesoffice.com/node-js-fundamentals-how-to-upgrade-the-node-js-version/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>How to get data from MongoDB into Node.js</title>
		<link>http://theholmesoffice.com/how-to-ge-data-from-mongodb-into-node-js/</link>
		<comments>http://theholmesoffice.com/how-to-ge-data-from-mongodb-into-node-js/#comments</comments>
		<pubDate>Fri, 28 Sep 2012 06:50:30 +0000</pubDate>
		<dc:creator>Simon Holmes</dc:creator>
				<category><![CDATA[Knowing Node]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[nodejs]]></category>

		<guid isPermaLink="false">http://theholmesoffice.com/?p=545</guid>
		<description><![CDATA[Most tutorials and info on the web show how to get data from MongoDB using Node.js, but don't cover what to do with it. Here I cover how to use the Node.js native driver to retrieve data from a MongoDB database, and how to use return it to a website in a useful and usable way.]]></description>
				<content:encoded><![CDATA[<p>So you&#8217;ve got a Node.js website, and created a MongoDB database - the big question &#8211; how do you connect the two? When we <a title="How to install MongoDB on Ubuntu for Node.js" href="http://theholmesoffice.com/how-to-install-mongodb-on-ubuntu-for-node-js/">installed MongoDB</a> we also installed the native MongoDB drivers for Node.js, so that&#8217;s a good start!</p>
<blockquote><p>If you have just arrived at this page, and want the context and framework for the rest of the files, check out my posts <a title="Creating an MVC framework for our Node.js page – getting ready for scalability" href="http://theholmesoffice.com/getting-ready-for-scalability-creating-an-mvc-framework-for-our-node-js-page/">Creating an MVC framework for our Node.js page – getting ready for scalability</a> and <a title="How to create a MongoDB database" href="http://theholmesoffice.com/how-to-create-a-mongodb-database/">How to create a MongoDB database</a></p></blockquote>
<p>In the MVC approach we will need to look at the &#8216;model&#8217; code and the &#8216;controller&#8217; code.</p>
<h2>Make your code &#8216;non-blocking&#8217;</h2>
<p>We will start off by looking at the controller. In a traditional stack you say:</p>
<ol>
<li>I&#8217;m going to go and get the data from the database</li>
<li>When I&#8217;ve got it I will do this with it</li>
</ol>
<p>This is no good for Node.js as it is a &#8216;blocking&#8217; operation &#8211; nothing else can happen until you have the data back. This is essentially what we did in the MVC framework with this bit of code in <em>home.js</em>.</p>
<pre class="brush: jscript; title: ; notranslate">
var teamlist = test_data.teamlist;
var strTeam = &quot;&quot;, i = 0;
for (i = 0; i&lt;teamlist.count;) {
 strTeam = strTeam + &quot;&lt;li&gt;&quot; + teamlist.teams[i].country + &quot;&lt;/li&gt;&quot;;
 i = i+1;
}
</pre>
<p>In that particular instance it was correct to do it this way, as we knew that the data-retrieval operation was non-blocking &#8211; we instantly pushed back a JSON object into the teamlist variable.</p>
<p>As pulling data from a database is a &#8216;blocking&#8217; operation we need to handle it differently. We need to say:</p>
<ol>
<li>Go get this data from the database</li>
<li>When you&#8217;ve got it, do this with it</li>
<li>Don&#8217;t disturb me until you&#8217;re done, I&#8217;ve got other things to do</li>
</ol>
<p>Sound like a callback function to you? It does to me!</p>
<h2>Creating the controller</h2>
<p>So let&#8217;s take a look at the new controller code and see what&#8217;s going on. I have created a new file for this, called <em>home-mongo.js</em>.</p>
<pre class="brush: jscript; title: ; notranslate">
var template = require('../views/template-main');
var mongo_data = require('../model/mongo-data');

exports.get = function(req, res) {
 mongo_data.teamlist(&quot;D&quot;,function(err,teamlist){
  if(!err){
   var strTeam = &quot;&quot;, i = 0;
   for (i = 0; i&lt;teamlist.count;) {
    strTeam = strTeam + &quot;&lt;li&gt;&quot; + teamlist.teams[i].country + &quot;&lt;/li&gt;&quot;;
    i = i+1;
   }
   strTeam = &quot;&lt;ul&gt;&quot; + strTeam + &quot;&lt;/ul&gt;&quot;
   res.writeHead(200, {'Content-Type': 'text/html'});
   res.write(
   template.build(&quot;Test web page on node.js&quot;,&quot;Hello there&quot;,&quot;&lt;p&gt;The teams in Group &quot; + teamlist.GroupName + &quot; for Euro 2012 are:&lt;/p&gt;&quot; + strTeam));
   res.end();
  }
  else{
   res.writeHead(200, {'Content-Type': 'text/html'});
   res.write(
   template.build(&quot;Oh dear&quot;,&quot;Database error&quot;,&quot;&lt;p&gt;Error details: &quot; + err + &quot;&lt;/p&gt;&quot;));
   res.end();
  }
 });
}
</pre>
<p>This is very similar to our <em>home.js </em>file, just a few important differences.</p>
<p>Firstly, we &#8216;require&#8217; a different model file, <em>mongo-data.js</em> that we will look at shortly.</p>
<p>Secondly, rather than pulling the data and doing something with it, we are using a callback function to say &#8220;do this with the data when you&#8217;ve got it&#8221;. What we are doing with the data is exactly the same as before. Note that we are sending the string &#8220;D&#8221; through as a variable; this is the string we will be searching for in the database.</p>
<p>Thirdly, through the callback function we are also sending instructions for what to do if an error occurs getting the data.</p>
<h2>Using Node.js to query the MongoDB data</h2>
<p>Before we look at the code, let&#8217;s think about what we&#8217;re looking to achieve:</p>
<ol>
<li>Connect to the MongoDB database</li>
<li>Have a function that is expecting a string variable and a callback</li>
<li>Search the database for the variable (a specific key of &#8216;GroupName&#8217;)</li>
<li>Create a JSON object if successful</li>
<li>Catch the error if not successful</li>
<li>Pass the JSON object or the error to the provided callback function</li>
<li>Close the database connection</li>
</ol>
<p>Easy? Not as hard as you might think. So here&#8217;s the code for the <em>mongo-data.js </em>file:</p>
<pre class="brush: jscript; title: ; notranslate">
var mongo = require('mongodb'),
 Server = mongo.Server,
 Db = mongo.Db;
var server = new Server('localhost', 27017, {auto_reconnect: true});
var db = new Db('euro2012', server);

var onErr = function(err,callback){
 db.close();
 callback(err);
};

exports.teamlist = function(gname,callback){
 db.open(function(err, db) {
  if(!err) {
   db.collection('teams', function(err, collection) {
    if(!err){
     collection.find({'GroupName':gname}).toArray(function(err, docs) {
      if(!err){
       db.close();
       var intCount = docs.length;
       if(intCount &gt; 0){
        var strJson = &quot;&quot;;
        for(var i=0; i&lt;intCount;){
         strJson += '{&quot;country&quot;:&quot;' + docs[i].country + '&quot;}'
         i=i+1;
         if(i&lt;intCount){strJson+=',';}
        }
        strJson = '{&quot;GroupName&quot;:&quot;'+gname+'&quot;,&quot;count&quot;:'+intCount+',&quot;teams&quot;:[' + strJson + &quot;]}&quot;
        callback(&quot;&quot;,JSON.parse(strJson));
       }
      }
      else{onErr(err,callback);}
     });//end collection.find
    }
    else{onErr(err,callback);}
   });//end db.collection
  }
  else{onErr(err,callback);}
 });// end db.open
};
</pre>
<p>The first five lines are all about setting up the MondoDB server and connecting to our database. You can learn more about that on the <a title="MongoDB Native driver info" href="http://mongodb.github.com/node-mongodb-native/api-articles/nodekoarticle1.html" target="_blank">MongoDB Native Driver GitHub page</a>.</p>
<p>Then we have a function <em>onErr</em> that we will call if we catch an error at any point.</p>
<p>Now comes the fun part! The MongoDB Native driver comes with a number of non-blocking functions built in. We are using three, to:</p>
<ol>
<li>Open our database (db.open)</li>
<li>Find the &#8216;collection&#8217; we specify (db.collection)</li>
<li>Find the documents in that collection that match the query we specify (collection.find().toArray)</li>
</ol>
<p>These all run as nested callbacks, which is where the code can get tricky to follow. To help with this I recommend adding a comment at the end of each callback function, like you can see in the code.</p>
<p>Counter-intuitively, the <em>collection.find</em> method doesn&#8217;t actually execute the query, that&#8217;s done by the <em>toArray</em> method. So that&#8217;s where we pass our next callback function. This part is where we take the <em>docs</em> returned by the database and use them to create a JSON object in the format we want.</p>
<p>The finished JSON object should look like this:</p>
<pre class="brush: jscript; gutter: false; title: ; notranslate">
{&quot;GroupName&quot;:&quot;D&quot;,&quot;count&quot;:4,&quot;teams&quot;:[{&quot;country&quot;:&quot;England&quot;},{&quot;country&quot;:&quot;France&quot;},{&quot;country&quot;:&quot;Sweden&quot;},{&quot;country&quot;:&quot;Ukraine&quot;}]}</pre>
<p>When the JSON object is complete we finally use the callback function, sending the object through.</p>
<p>The last thing we need to do &#8211; if you&#8217;ve been playing along at home &#8211; is update our router file to call the controller.</p>
<p>So in <em>router.js</em> file just change the home controller to be home-mongo, like so:</p>
<pre class="brush: jscript; title: ; notranslate">

if (path === '/' || path === '/home') {
 require('./controllers/home-mongo').get(req, res);
}
</pre>
<p>If you run the site, you shouldn&#8217;t really see any change, as all of the data manipulation is happening behind the scenes.<br />
<img class="alignnone size-full wp-image-563" title="Node.js website pulling data from MongoDB" src="http://theholmesoffice.com/wp-content/uploads/2012/09/Screenshot-from-2012-09-28-074024.png" alt="" width="633" height="442" /></p>
<p>Next up we&#8217;ll see if we can simplify this process by <a title="Mongoose and Node.js tutorial" href="http://theholmesoffice.com/mongoose-and-node-js-tutorial/">using Mongoose, Node.js and MongoDB together</a>.</p>
<blockquote><p><strong>Get the source code</strong></p>
<p><strong></strong>The source code for this and my other tutorials on Node.js is available on GitHub here: <a title="Knowing Node source code on GitHub" href="https://github.com/simonholmes/knowing-node/" target="_blank">https://github.com/simonholmes/knowing-node/</a></p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://theholmesoffice.com/how-to-ge-data-from-mongodb-into-node-js/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to create a MongoDB database</title>
		<link>http://theholmesoffice.com/how-to-create-a-mongodb-database/</link>
		<comments>http://theholmesoffice.com/how-to-create-a-mongodb-database/#comments</comments>
		<pubDate>Wed, 25 Jul 2012 06:46:07 +0000</pubDate>
		<dc:creator>Simon Holmes</dc:creator>
				<category><![CDATA[Knowing Node]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://theholmesoffice.com/?p=491</guid>
		<description><![CDATA[Taking you through how to create a database in MongoDB, save some data to it and also return the data from. All in Ubuntu from the Mongo shell. It also covers some of the shifts in mindset needed when approaching from a "traditional" relational database.]]></description>
				<content:encoded><![CDATA[<p>So we&#8217;ve got a <a title="Creating an MVC framework for our Node.js page – getting ready for scalability" href="http://theholmesoffice.com/getting-ready-for-scalability-creating-an-mvc-framework-for-our-node-js-page/">Node.js website</a> ready and waiting for some database data. We&#8217;ve also got <a title="How to install MongoDB on Ubuntu for Node.js" href="http://theholmesoffice.com/how-to-install-mongodb-on-ubuntu-for-node-js/">MongoDB installed</a>. So let&#8217;s create a database and put some data into it.</p>
<h3>Step 1: don&#8217;t create a database</h3>
<p>Hang on Simon, are you sure you&#8217;ve got that right? Yep! There is no create database command in MongoDB. If you come from a traditional stack, like me, this is quite a weird concept. Surely the first thing to do is create the actual file and define a schema? Not so with MongoDB. With MongoDB you create a database the first time you save data into it.</p>
<p>Let&#8217;s try that out.</p>
<p>When we installed MongoDB we tested the installation by displaying a list of the databases on the machine. So let&#8217;s drop into the Mongo shell and do that. A couple of terminal commands (don&#8217;t type the &#8216;$&#8217; or the &#8216;&gt;&#8217; symbols, here &#8216;$&#8217; indicates a terminal prompt and &#8216;&gt;&#8217; a Mongo prompt):</p>
<pre class="brush: bash; title: ; notranslate">$ mongo
&gt; show dbs
</pre>
<p>You should see something like this get returned:<br />
<a href="http://174.120.61.99/~simonh/wp-content/uploads/2012/07/screenshot-from-2012-07-13-0658121.png"><img class="alignnone size-full wp-image-493" title="List of MongoDB databases" src="http://174.120.61.99/~simonh/wp-content/uploads/2012/07/screenshot-from-2012-07-13-0658121.png" alt="List of MongoDB databases" width="580" height="111" /></a></p>
<h3>Step 2: &#8220;Use&#8221; the database you wish to create</h3>
<p>As we mentioned earlier, rather than explicitly creating a database, MongoDB will create a database when it first has data saved to. In order to save data, we need to connect to our new database even though it doesn&#8217;t exist yet. Sounds odd, but it&#8217;s really easy. Simply enter this command into the Mongo shell:</p>
<pre class="brush: bash; title: ; notranslate">use euro2012</pre>
<p>In this instance we are going to use a database called &#8220;euro2012&#8243;.</p>
<p>If you use the <em>show dbs </em>command again, you will see that the database hasn&#8217;t been created yet.</p>
<p><a href="http://174.120.61.99/~simonh/wp-content/uploads/2012/07/screenshot-from-2012-07-13-0658121.png"><img title="List of MongoDB databases" src="http://174.120.61.99/~simonh/wp-content/uploads/2012/07/screenshot-from-2012-07-13-0658121.png" alt="List of MongoDB databases" width="580" height="111" /></a></p>
<h3>Step 3: Insert some data into the MongoDB database</h3>
<p>Here&#8217;s another difference of MongoDB from traditional relational databases: there are no tables, rows or columns. In their place, MongoDB uses <em>collections</em> and <em>objects</em>. Think of collections as tables, and objects as table rows. The main difference is that we&#8217;re not stuck into a rigid column structure.</p>
<p>Here&#8217;s how the MongoDB guys explain it themselves (<a title="MongoDB introduction (opens in new window)" href="http://www.mongodb.org/display/DOCS/Introduction" target="_blank">source</a>):</p>
<blockquote>
<ul>
<li>A <strong>database</strong> holds a set of collections</li>
<li>A <strong>collection</strong> holds a set of documents</li>
<li>A <strong>document</strong> is a set of fields</li>
<li>A <strong>field</strong> is a key-value pair</li>
<li>A <strong>key</strong> is a name (string)</li>
<li>A <strong>value</strong> is a
<ul>
<li>basic type like string, integer, float, timestamp, binary, etc.,</li>
<li>a document, or</li>
<li>an array of values</li>
</ul>
</li>
</ul>
</blockquote>
<p>You can explicitly create collections, but they can also be created the first time you use them. We&#8217;ll do the latter here. In the Mongo shell enter the following:</p>
<pre class="brush: bash; title: ; notranslate">db.teams.save({country:&quot;England&quot;,GroupName:&quot;D&quot;}) </pre>
<p>That will create a new <em>collection </em>called &#8220;teams&#8221;, and save an <em>object</em> with two <em>fields </em>&#8220;country&#8221; and &#8220;GroupName&#8221;. Crucially, this will now also save our database. Check that it has been created by running <em>show dbs </em> again.</p>
<p><img class="alignnone size-full wp-image-495" title="List of MongoDB databases" src="http://174.120.61.99/~simonh/wp-content/uploads/2012/07/screenshot-from-2012-07-23-072619.png" alt="List of MongoDB databases" width="580" height="96" /></p>
<p>You should now see that our new database has been added to the list.</p>
<p>Now add the rest of the data using the following command in the Mongo shell:</p>
<pre class="brush: bash; title: ; notranslate">db.teams.save({country:&quot;France&quot;,GroupName:&quot;D&quot;})
db.teams.save({country:&quot;Sweden&quot;,GroupName:&quot;D&quot;})
db.teams.save({country:&quot;Ukraine&quot;,GroupName:&quot;D&quot;})</pre>
<h3>Step 3: testing by reading the data back out.</h3>
<p>Having put some data in, and tested that the database has been saved, we should now verify that the data we entered has been saved as we expected it to be.</p>
<p>Run a simple &#8220;find&#8221; on the collection to return all objects by entering this into the Mongo shell:</p>
<pre class="brush: bash; title: ; notranslate">db.teams.find()</pre>
<p>This should return you something like this:<br />
<img class="alignnone size-full wp-image-496" title="collection.find() command in MongoDB" src="http://174.120.61.99/~simonh/wp-content/uploads/2012/07/screenshot-from-2012-07-14-084501.png" alt="collection.find() command in MongoDB" width="580" height="96" /></p>
<p>Perfect! We&#8217;ve created a MongoDB database and saved our information into it <img src='http://theholmesoffice.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Next up, we&#8217;ll take a look at how to use this data in our site, by connecting MongoDB to Node.js.</p>
]]></content:encoded>
			<wfw:commentRss>http://theholmesoffice.com/how-to-create-a-mongodb-database/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to install MongoDB on Ubuntu for Node.js</title>
		<link>http://theholmesoffice.com/how-to-install-mongodb-on-ubuntu-for-node-js/</link>
		<comments>http://theholmesoffice.com/how-to-install-mongodb-on-ubuntu-for-node-js/#comments</comments>
		<pubDate>Mon, 16 Jul 2012 06:30:33 +0000</pubDate>
		<dc:creator>Simon Holmes</dc:creator>
				<category><![CDATA[Knowing Node]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://theholmesoffice.com/?p=476</guid>
		<description><![CDATA[Part of the Knowing Node collection, this tutorial demonstrates how to install MongoDB on Ubuntu, test the installation using the MongoDB shell and run MongoDB as a service. It also covers how to install the native MongoDB drivers for Node.js.]]></description>
				<content:encoded><![CDATA[<p>Having a <a title="Creating an MVC framework for our Node.js page – getting ready for scalability" href="http://theholmesoffice.com/getting-ready-for-scalability-creating-an-mvc-framework-for-our-node-js-page/">node.js website</a> without a database in the backend is going to be pretty limiting! So let&#8217;s address that.</p>
<p>There are a whole bunch of databases that we could use, but we&#8217;re going to go with a popular choice for Node.js development, <a title="MongoDB" href="http://www.mongodb.org/" target="_blank">MongoDB</a>. In their own words:</p>
<blockquote><p>MongoDB (from &#8220;hu<strong>mongo</strong>us&#8221;) is a scalable, high-performance, <a href="http://www.mongodb.org/display/DOCS/Source+Code">open source</a> NoSQL database.</p></blockquote>
<h3>Installing MongoDB on Ubuntu</h3>
<p>If you Google how to do this you might get put off, as you&#8217;ll find a load of pages with different workarounds to get MongoDB installed correctly, Q&amp;A threads on fixing install errors etc. Fortunately this has all been fixed, and it&#8217;s now super easy to install MongoDB on Ubuntu.</p>
<p>Open a terminal window and enter:</p>
<pre class="brush: bash; title: ; notranslate">sudo apt-get install mongodb</pre>
<p>That&#8217;s it! As soon as that&#8217;s finished downloading and processing you&#8217;ll have MongoDB installed.</p>
<h3>Testing your MongoDB install</h3>
<p>You want to test to make sure that it&#8217;s installed correctly? Fair enough. Let&#8217;s start it up as an <a title="Ubuntu Upstart" href="http://upstart.ubuntu.com/" target="_blank">Upstart</a> service (more on Upstart at another time).</p>
<h4>Start the MongoDB service</h4>
<p>In terminal enter:</p>
<pre class="brush: bash; title: ; notranslate">sudo service mongodb start</pre>
<p>You should now see a confirmation along the lines of &#8220;mongodb start/running, process 15251&#8243;</p>
<h4>Using the MongoDB command line shell</h4>
<p>MongoDB comes with a command line shell. We&#8217;ll use this to verify everything is running correctly.</p>
<p>To enter the MongoDB shell, in terminal simply enter:</p>
<pre class="brush: bash; title: ; notranslate">mongo</pre>
<p>This should tell you the shell version and connect you to the &#8216;test&#8217; database that ships with Mongo. You should see something like this:<br />
<img title="Entering the MongoDB shell in terminal" src="http://174.120.61.99/~simonh/wp-content/uploads/2012/07/screenshot-from-2012-07-12-084045.png" alt="Entering the MongoDB shell in terminal" width="580" height="111" /></p>
<p>The &#8220;&gt;&#8221; indicator at the start of a new line shows that you are now working in the MongoDB shell, not the Ubuntu command line.</p>
<h4>Listing all databases</h4>
<p>While we&#8217;re here, let&#8217;s see what MongoDB database have been created during installation.</p>
<p>In the MongoDB shell, enter this command to list all databases:</p>
<pre class="brush: bash; title: ; notranslate">show dbs</pre>
<p>You should then see something like this screenshot, showing two databases and their sizes.<br />
<img title="Listing installed databases in MongoDB" src="http://174.120.61.99/~simonh/wp-content/uploads/2012/07/screenshot-from-2012-07-13-065812.png" alt="Listing installed databases in MongoDB" width="580" height="111" /></p>
<h4>Exiting the MongoDB shell</h4>
<p>Press Ctrl+D to exit the MongoDB shell and return to the terminal command line interface.</p>
<h3>How to install the native MongoDB drivers for Node.js</h3>
<p>So having got MongoDB installed, we want to make sure that our Node.js applications will be able to use it. For this we need to install the native driver. <em>Note: there are actually loads of middleware modules to simplify and extend the possibilities which we&#8217;ll cover at another time.</em> For now we&#8217;ll stick to the basics so that we&#8217;ve got a solid foundation to build upon.</p>
<p>To install the native MongoDB drivers we&#8217;ll use NPM, so head to terminal and enter:</p>
<pre class="brush: bash; title: ; notranslate">npm install mongodb --mongodb:native</pre>
<p>This will run through the installation process, downloading everything we need to get MongoDB and Node.js talking to each other!</p>
<p>Happy days! Next up we&#8217;ll be <a title="How to create a MongoDB database" href="http://theholmesoffice.com/how-to-create-a-mongodb-database/" target="_blank">creating a MongoDB database</a> so that we can actually use it with our <a title="Creating an MVC framework for our Node.js page – getting ready for scalability" href="http://theholmesoffice.com/getting-ready-for-scalability-creating-an-mvc-framework-for-our-node-js-page/" target="_blank">Node.js MVC site</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://theholmesoffice.com/how-to-install-mongodb-on-ubuntu-for-node-js/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Creating an MVC framework for our Node.js page &#8211; getting ready for scalability</title>
		<link>http://theholmesoffice.com/getting-ready-for-scalability-creating-an-mvc-framework-for-our-node-js-page/</link>
		<comments>http://theholmesoffice.com/getting-ready-for-scalability-creating-an-mvc-framework-for-our-node-js-page/#comments</comments>
		<pubDate>Mon, 09 Jul 2012 06:44:20 +0000</pubDate>
		<dc:creator>Simon Holmes</dc:creator>
				<category><![CDATA[Knowing Node]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[nodejs]]></category>

		<guid isPermaLink="false">http://theholmesoffice.com/?p=416</guid>
		<description><![CDATA[This tutorial takes you through how to create and use a simple MVC architecture in Node.js. It shows you how to organise your code in a maintainable and scalable way, whilst introducing some of the core concepts behind Node.js.]]></description>
				<content:encoded><![CDATA[<p>Having got our <a title="How to build a simple webpage in Node.js" href="http://theholmesoffice.com/how-to-build-a-simple-webpage-in-node-js/">simple webpage working in Node.js</a>, it&#8217;s now time to think bigger. But we can&#8217;t very well create an entire website in just one file, so let&#8217;s look at how to create a framework upon which we can base our future development.</p>
<p>If you&#8217;ve spent much time as a developer you&#8217;ll know that the key to maintainability is separation of concerns across your projects. If you&#8217;ve been developing a long time, since before such architectures were really discussed, then you probably learned the hard way. Anyhow, what we mean, and what we want to achieve is to separate out our data, logic and presentation.</p>
<h3>MVC &#8211; The Model-View-Controller approach</h3>
<p>A very popular approach for web sites &amp; web apps &#8211; and the one we&#8217;ll be working with &#8211; is MVC, which stands for model, view, controller. This makes distinctions between the model (data), view (presentation) and controllers (logic).</p>
<p>The diagram below shows how a standard MVC request/response loop looks:<br />
<img class="alignnone size-full wp-image-456" title="MVC diagram" alt="MVC diagram" src="http://174.120.61.99/~simonh/wp-content/uploads/2012/06/mvc-diagram2.png" width="552" height="171" /></p>
<p>In short these are the steps:</p>
<ol>
<li>Request comes in to the Controller</li>
<li>Controller makes a request to the model</li>
<li>Model returns a response to the controller</li>
<li>The controller (normally) performs some operations using the response from the model</li>
<li>The controller sends a response to the view</li>
<li>The view renders the response</li>
</ol>
<p>In Node.js, because we are also creating the webserver too, we need to add three steps in at the beginning:</p>
<ol>
<li>Request comes in to server</li>
<li>Server sends request to router</li>
<li>Router sends request to appropriate controller</li>
</ol>
<p>Looking at this, we can see that we are going to need the following objects (or collections of objects):</p>
<ol>
<li>Server &#8211; to listen to and respond to HTTP requests</li>
<li>Router &#8211; to send the incoming requests to the correct controller</li>
<li>Controllers &#8211; to perform operations &amp; interrogate the data</li>
<li>Model &#8211; to provide the data</li>
<li>Views &#8211; to provide the HTML rendering we&#8217;re going to see in the browser</li>
</ol>
<h3>Building our framework</h3>
<p>To keep things clean, lets create a new folder to put our site in.</p>
<h4>Creating the node.js server</h4>
<p>Create a file called server.js with the following content:</p>
<pre class="brush: jscript; gutter: true; title: ; notranslate">

var http_IP = '127.0.0.1';
var http_port = 8899;
var http = require('http');
var server = http.createServer(function (req, res) {
 require('./router').get(req, res);
});// end server()
server.listen(http_port,http_IP);
console.log('listening to http://' + http_IP + ':' + http_port);

</pre>
<p>The only new thing there, is that rather than outputting anything directly here, we are calling in a &#8216;router&#8217; module and sending it the request &amp; response object. This makes sense if you look back at the steps the application needs to take: <em>server sends request to router.</em></p>
<h4>Building the router</h4>
<p>In the same folder as the server.js file, create a new file called router.js and save it with the following content:</p>
<pre class="brush: jscript; gutter: true; title: ; notranslate">

var url = require('url');
var fs = require('fs');

exports.get = function(req, res) {
 req.requrl = url.parse(req.url, true);
 var path = req.requrl.pathname;
 if (/.(css)$/.test(path)){
  res.writeHead(200, {'Content-Type': 'text/css'});
  fs.readFile(__dirname + path, 'utf8', function (err, data){
   if (err) throw err;
   res.write(data, 'utf8');
   res.end();
  });
 } else {
  if (path === '/' || path === '/home') {
   require('./controllers/home').get(req, res);
  } else {
   require('./controllers/404').get(req, res);
  }
 }
}

</pre>
<p>In the router we are doing a few different things:</p>
<ol>
<li>Importing the URL and FileSystem (fs) modules that come as part of your node.js install</li>
<li>Exporting a function called &#8220;get&#8221; &#8211; this allows our server file to use this function, passing the request and response objects through</li>
<li>Getting the path of the URL request</li>
<li>Testing to see whether the request is for a CSS file and loading it in if so. There are a number of different ways of handling static files, but this method is fine for what we&#8217;re doing here</li>
<li>Sending the request to the correct controller, if it&#8217;s not for a CSS file</li>
</ol>
<p>At this point in our development, it&#8217;s number 5 we are interested in. We are checking for two URL paths &#8216;/&#8217; and &#8216;/home&#8217; which will route to a controller called &#8216;home&#8217;. We then send any other URL requests to a controller called &#8217;404&#8242;. Let&#8217;s take a look at these controllers.</p>
<h4>Building the controllers</h4>
<p>Create a folder in the root of your site, called &#8216;controllers&#8217;. Inside this folder create a file called &#8216;home.js&#8217; with the following content:</p>
<pre class="brush: jscript; gutter: true; title: ; notranslate">

var template = require('../views/template-main');
var test_data = require('../model/test-data');

exports.get = function(req, res) {
 var teamlist = test_data.teamlist;
 var strTeam = &quot;&quot;, i = 0;
 for (i = 0; i&lt;teamlist.count;) {
 strTeam = strTeam + &quot;&lt;li&gt;&quot; + teamlist.teams[i].country + &quot;&lt;/li&gt;&quot;;
 i = i+1;
 }
 strTeam = &quot;&lt;ul&gt;&quot; + strTeam + &quot;&lt;/ul&gt;&quot;
 res.writeHead(200, {'Content-Type': 'text/html'});
 res.write(
 template.build(&quot;Test web page on node.js&quot;,&quot;Hello there&quot;,&quot;&lt;p&gt;The teams in Group &quot; + teamlist.GroupName + &quot; for Euro 2012 are:&lt;/p&gt;&quot; + strTeam));
 res.end();
}

</pre>
<p>Right at the top of this file you can see that we are including the rest of our MVC structure the <em>model</em> and the <em>view</em>. Referring back to the diagram we remember that the controller should do two main things:</p>
<ol>
<li>The controller (normally) performs some operations using the response from the model</li>
<li>The controller sends a response to the view</li>
</ol>
<h5>Performing operations on model data</h5>
<p>Our task here is quite simple: get a data object (<em>teamlist</em>) and create a HTML string putting the items into an unordered list. In the next step we&#8217;ll see how we create this data.</p>
<h5>Sending a response to the view</h5>
<p>We will use a view (think template) called template-main, which we will create in a few minutes. Note that through the template.build function that we are only sending three content items; within the controller there is no reference to how this content will be displayed. In this example you will notice that we are sending through the HTML for the &lt;ul&gt; list, there are arguments against having even this level of markup in a controller, but we&#8217;re going for a simple example here so let&#8217;s keep it in!</p>
<h4>Getting data from the model</h4>
<p>In a future post we&#8217;ll see how we can extend this demo by getting the data out of a database, but for the sake of remaining focused on the point right now we&#8217;ll fake it by creating and returning a JSON object.</p>
<p>So, create a folder in the root of your site called &#8216;model&#8217;. Inside this folder create a new file called &#8216;test-data.js&#8217; with the following content:</p>
<pre class="brush: jscript; gutter: true; title: ; notranslate">

var thelist = function() {
 var objJson = {&quot;GroupName&quot;:&quot;D&quot;,&quot;count&quot;:4,&quot;teams&quot;:[{&quot;country&quot;:&quot;England&quot;}, {&quot;country&quot;:&quot;France&quot;}, {&quot;country&quot;:&quot;Sweden&quot;}, {&quot;country&quot;:&quot;Ukraine&quot;}]};
 return objJson;
};

exports.teamlist = thelist();
</pre>
<p>Through the export function we are exposing the function <em>thelist()</em> which itself is returning a JSON object. This is how &#8211; for now &#8211; we will return a data object to the <em>teamlist</em> in our controller.</p>
<h4>Using a view template to create the HTML page</h4>
<p>Now that we have our controller pulling in some data from the model and doing something with it, we want to show the outcome in a webpage. We&#8217;ve seen that we&#8217;re going to send the data to a <em>build</em> function in a view template, so let&#8217;s create that now.</p>
<p>Create a folder in the root of your site called &#8216;views&#8217;. Inside this folder create a new file called &#8216;template-main.js&#8217; with the following content:</p>
<pre class="brush: jscript; gutter: true; title: ; notranslate">

exports.build = function(title, pagetitle, content) {
 return ['&lt;!doctype html&gt;',
 '&lt;html lang=&quot;en&quot;&gt;\n&lt;head&gt;n&lt;meta charset=&quot;utf-8&quot;&gt;\n&lt;title&gt;{title}&lt;/title&gt;',
 '&lt;link rel=&quot;stylesheet&quot; href=&quot;/assets/style.css&quot; /&gt;\n&lt;/head&gt;',
 '&lt;body&gt;&lt;h1&gt;{pagetitle}&lt;/h1&gt;',
 '&lt;div id=&quot;content&quot;&gt;{content}&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;'
 ].join('\n')
 .replace(/{title}/g, title)
 .replace(/{pagetitle}/g, pagetitle)
 .replace(/{content}/g, content);
}
</pre>
<p>Here we are directly exposing the <em>build </em>function, which takes three parameters: <em>title</em>, <em>pagetitle</em> and <em>content</em>.</p>
<p>The first thing we are doing here is joining an array of strings, placing a new line &#8216;n&#8217; between them. This creates one long string of HTML that will render on separate lines leaving the source code more readable. This string is the basis of our template, and contains a number of placeholders for the content items <em>{title}</em>, <em>{pagetitle}</em> and <em>{content}</em>.</p>
<p>Naturally then, the second step here is to replace these placeholders with the actual content sent through via the function arguments. The three <em>replace </em>functions are doing exactly that, running a very simple regular expression to globally change all occurrences found in the string. This means that you can have {title} in several places in your template, and each will get replaced. Note that we are also chaining the join and replace commands; the separate lines are for readability. Seeing as it works when laid out like this there is little sense in putting them all on one line and making the script harder to read.</p>
<h4>Using a static CSS file</h4>
<p>You may have noticed that in the HTML view template that we are referencing a static CSS file; remember in the router how we created a statement checking for the .css file extension? Now is the time to implement it.</p>
<p>In the root of your site create a folder called &#8216;assets&#8217;. Inside this folder create a text file called &#8216;style.css&#8217; with the following content:</p>
<pre class="brush: css; gutter: true; title: ; notranslate">
* {font-family:arial, sans-serif;}
</pre>
<p>This isn&#8217;t the most complex CSS file in the world, but the change in font is enough for us to know that it is working!</p>
<h4>Creating a 404 page</h4>
<p>The final piece of our site is to create our 404 page. We already have a suitable template &#8211; our template-main view &#8211; so we&#8217;ll re-use that. Our router is also already set to send people to a 404 if it doesn&#8217;t recognise the URL path requested. So all that remains for us to do is to create the controller.</p>
<p>In your &#8216;controllers&#8217; folder create a new file called &#8217;404.js&#8217; with the following content:</p>
<pre class="brush: jscript; gutter: true; title: ; notranslate">
var template = require('../views/template-main');
exports.get = function(req, res) {
 res.writeHead(404, {'Content-Type': 'text/html'});
 res.write(
 template.build(&quot;404 - Page not found&quot;,&quot;Oh noes, it's a 404&quot;,&quot;&lt;p&gt;This isn't the page you're looking for...&lt;/p&gt;&quot;));
 res.end();
}
</pre>
<p>You should be able to see what we&#8217;re doing here. Using the same template - <em>views/template-main </em>- we send it three items of content. The only difference this time is that we have changed the status code of the response &#8211; in the <em>res.writeHead</em> function &#8211; from 200 (Ok) to 404 (not found).</p>
<h3>Let&#8217;s run the site!</h3>
<p>That&#8217;s all the pieces of our MVC framework in place, so let&#8217;s try out our site. In terminal cd into the root folder of your site and run it with the command:</p>
<pre class="brush: bash; gutter: true; title: ; notranslate">node server.js</pre>
<p>Now head to 127.0.0.1:8899 in browser and you should see something like this:<br />
<img class="alignnone size-full wp-image-449" title="The homepage of our site running in node.js" alt="The homepage of our site running in node.js" src="http://174.120.61.99/~simonh/wp-content/uploads/2012/06/screenshot-from-2012-06-27-222058.png" width="580" height="415" /></p>
<p>Let&#8217;s test our other path from the router, by navigating to 127.0.0.1:8899/home<br />
<img class="alignnone size-full wp-image-452" title="Our node.js homepage from the URL path /home" alt="Our node.js homepage from the URL path /home" src="http://174.120.61.99/~simonh/wp-content/uploads/2012/06/screenshot-from-2012-06-27-221927.png" width="580" height="415" /></p>
<p>Finally, let&#8217;s test our 404 page, by going to a URL that we haven&#8217;t added to the router, for example 127.0.0.1:8899/test<br />
<img class="alignnone size-full wp-image-453" title="Our node.js 404 page" alt="Our node.js 404 page" src="http://174.120.61.99/~simonh/wp-content/uploads/2012/06/screenshot-from-2012-06-27-222009.png" width="580" height="415" /></p>
<h4>Success!</h4>
<p>So there we have it. We now have a working website in node.js written in a maintainable and scalable MVC framework. In future posts I will take a look at how to remove some of the pain by using the express.js framework, and also how to get the data from a MongoDB database.</p>
<blockquote><p><strong>Get the source code</strong></p>
<p>The source code for this and my other tutorials on Node.js is available on GitHub here: <a title="Knowing Node source code on GitHub" href="https://github.com/simonholmes/knowing-node/" target="_blank">https://github.com/simonholmes/knowing-node/</a></p></blockquote>
<div id='Knowing_Node_book' class='widgets_on_page'>
    <ul><li id="text-3" class="widget widget_text">			<div class="textwidget"><p><a href="http://www.knowingnode.com/?utm_source=theholmesoffice&utm_medium=blog&utm_content=post-foot&utm_campaign=tho_blog" target="_blank" title="Visit knowingnode.com (opens in a new window)"><img src="http://theholmesoffice.com/wp-content/uploads/2013/03/KnowingNodeBookBanner.png" width="500" height="131" alt="Find this useful? Check out my book, Knowing Node" /></a></p></blockquote></div>
		</li></ul>
  </div><!-- widgets_on_page -->
]]></content:encoded>
			<wfw:commentRss>http://theholmesoffice.com/getting-ready-for-scalability-creating-an-mvc-framework-for-our-node-js-page/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to build a simple webpage in Node.js</title>
		<link>http://theholmesoffice.com/how-to-build-a-simple-webpage-in-node-js/</link>
		<comments>http://theholmesoffice.com/how-to-build-a-simple-webpage-in-node-js/#comments</comments>
		<pubDate>Mon, 02 Jul 2012 07:10:40 +0000</pubDate>
		<dc:creator>Simon Holmes</dc:creator>
				<category><![CDATA[Knowing Node]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[web-dev]]></category>
		<category><![CDATA[webserver]]></category>

		<guid isPermaLink="false">http://theholmesoffice.com/?p=387</guid>
		<description><![CDATA[Building your first simple webpage in Node.js, I take a look at what is involved and break down all of the pieces.]]></description>
				<content:encoded><![CDATA[<p>So you&#8217;ve got <a title="Installing node.js on Ubuntu for the first time" href="http://theholmesoffice.com/installing-node-js-on-ubuntu-for-the-first-time/">Node.js installed</a>, and <a title="Testing your Node.js install" href="http://theholmesoffice.com/testing-your-node-js-install/">tested that&#8217;s it&#8217;s working</a>? Great! Let&#8217;s see it in action and dive straight into building a one page website.</p>
<p>For these early tests it&#8217;s fine to just use a simple text editor, I&#8217;ve been using Gedit on Ubuntu. Just type gedit into terminal to get it started.</p>
<h3>Create your file</h3>
<p>Create a new text document and save it as app.js.  Enter in the text below and then we&#8217;ll take a look at what&#8217;s going on.</p>
<pre class="brush: jscript; title: ; notranslate">
var http = require('http');
http.createServer(function (req, res) {
 res.writeHead(200, {'Content-Type': 'text/html'});
 res.write('&lt;!doctype html&gt;\n&lt;html lang=&quot;en&quot;&gt;\n' +
 '&lt;head&gt;\n&lt;meta charset=&quot;utf-8&quot;&gt;\n&lt;title&gt;Test web page on node.js&lt;/title&gt;\n' +
 '&lt;style type=&quot;text/css&quot;&gt;* {font-family:arial, sans-serif;}&lt;/style&gt;\n' +
 '&lt;/head&gt;\n&lt;body&gt;\n&lt;h1&gt;Euro 2012 teams&lt;/h1&gt;\n' +
 '&lt;div id=&quot;content&quot;&gt;&lt;p&gt;The teams in Group D for Euro 2012 are:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;England&lt;/li&gt;&lt;li&gt;France&lt;/li&gt;&lt;li&gt;Sweden&lt;/li&gt;&lt;li&gt;Ukraine&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;' +
 '\n&lt;/body&gt;\n&lt;/html&gt;');
 res.end();
}).listen(8888, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8888');
</pre>
<p>Ok great, so what are we looking at here?</p>
<h3>Creating the webserver</h3>
<p>The first thing to remember &#8211; and a big change to get used to if you&#8217;re coming over from a Microsoft IIS stack, or an Apache based stack &#8211; is that with Node.js there is no webserver until you create it. And that&#8217;s what our first two lines are doing.</p>
<h4>Calling the HTTP module</h4>
<p>Starting at the top, the very first thing we do is load in the pre-prepared HTTP module that ships as part of node. You&#8217;ll see this type of syntax a lot, as Node.js programming uses a lot of modules. As a best practice it&#8217;s a good idea to set the variable name to match the module name.</p>
<pre class="brush: jscript; gutter: false; title: ; notranslate">var http = require('http');</pre>
<h4>Create the server</h4>
<p>Stripping out the callback function to make it a little more clear, we can look at the createServer method of HTTP like this:</p>
<pre class="brush: jscript; gutter: false; title: ; notranslate">http.createServer(function(req, res){ }).listen(8888, '127.0.0.1');</pre>
<p>What we are doing here is creating a HTTP server to listen to requests (req) made to port 8888 on the IP address 127.0.0.1, and also send response objects (res)  back to the same IP and port.  The IP address 127.0.0.1  is common across many OS&#8217;s as the &#8216;localhost&#8217; server.</p>
<p>We also output a message to the console to show that we&#8217;ve reached the end of the script and that the server is running:</p>
<pre class="brush: jscript; gutter: false; title: ; notranslate">console.log('Server running at http://127.0.0.1:8888');</pre>
<h3>But what about the middle bit?!</h3>
<p>Okay, so in a nutshell what we&#8217;re doing here is responding to any request in exactly the same way. Let&#8217;s break that response down.</p>
<h4>res.writeHead()</h4>
<p>The first part of the response object is another item that you&#8217;re probably not used to really thinking about if you&#8217;re coming from a traditional stack where the web-server does all this for you. We need to send the <a title="List of HTTP header fields on Wikipedia (opens in new window)" href="http://en.wikipedia.org/wiki/List_of_HTTP_header_fields" target="_blank">HTTP headers</a>. Here we&#8217;re  just sending the HTTP status code and content type. So to say that the request was successful, and that we&#8217;re sending back HTML content we type:</p>
<pre class="brush: jscript; gutter: false; title: ; notranslate">res.writeHead(200, {'Content-Type': 'text/html'});</pre>
<h4>res.write()</h4>
<p>Next we want to send some content back to the response object. Here we&#8217;re doing it all as one long string:</p>
<pre class="brush: jscript; gutter: false; title: ; notranslate">
res.write('&lt;!doctype html&gt;\n&lt;html lang=&quot;en&quot;&gt;\n' +
 '&lt;head&gt;\n&lt;meta charset=&quot;utf-8&quot;&gt;\n&lt;title&gt;Test web page on node.js&lt;/title&gt;\n' +
 '&lt;style type=&quot;text/css&quot;&gt;* {font-family:arial, sans-serif;}&lt;/style&gt;\n' +
 '&lt;/head&gt;n&lt;body&gt;\n&lt;h1&gt;Euro 2012 teams&lt;/h1&gt;\n' +
 '&lt;div id=&quot;content&quot;&gt;&lt;p&gt;The teams in Group D for Euro 2012 are:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;England&lt;/li&gt;&lt;li&gt;France&lt;/li&gt;&lt;li&gt;Sweden&lt;/li&gt;&lt;li&gt;Ukraine&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;' +
 '\n&lt;/body&gt;\n&lt;/html&gt;');
</pre>
<h4>res.end()</h4>
<p>To tell the server that we&#8217;ve reached the end of the response object we type:</p>
<pre class="brush: jscript; gutter: false; title: ; notranslate">res.end()</pre>
<h3>Run your node.js site!</h3>
<p>Starting your node.js server is nice is simple. In terminal cd into the directory that you saved your app.js file and type:</p>
<pre class="brush: jscript; title: ; notranslate">node app.js</pre>
<p>All being well you&#8217;ll see your console message output to the terminal:<br />
<img title="Node.js server running in terminal" src="http://174.120.61.99/~simonh/wp-content/uploads/2012/06/screenshot-from-2012-06-15-175951.png" alt="Node.js server running in terminal" width="580" height="82" /></p>
<h3>Open your node.js site in a browser</h3>
<p>Go to your browser and navigate to http://127.0.0.1:8888. Cross your fingers, blink twice and you should see this:<br />
<img title="Node.js website running locally" src="http://174.120.61.99/~simonh/wp-content/uploads/2012/06/screenshot-from-2012-06-15-180317.png" alt="Node.js website running locally" width="580" height="415" /></p>
<p>Hurrah and huzzah! You&#8217;ve got a webpage running in Node.js <img src='http://theholmesoffice.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Next time we&#8217;ll take a look at how to build this in a more scalable way, creating a <a title="Creating an MVC framework for our Node.js page – getting ready for scalability" href="http://theholmesoffice.com/getting-ready-for-scalability-creating-an-mvc-framework-for-our-node-js-page/">basic MVC framework in Node.js</a>!</p>
<blockquote><p><strong>Get the source code</strong></p>
<p><strong></strong>The source code for this and my other tutorials on Node.js is available on GitHub here: <a title="Knowing Node source code on GitHub" href="https://github.com/simonholmes/knowing-node/" target="_blank">https://github.com/simonholmes/knowing-node/</a></p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://theholmesoffice.com/how-to-build-a-simple-webpage-in-node-js/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
<!-- WP Super Cache is installed but broken. The constant WPCACHEHOME must be set in the file wp-config.php and point at the WP Super Cache plugin directory. -->
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Served from: theholmesoffice.com @ 2013-05-23 10:24:38 -->