Archive for the ‘nodejs’ Category

Building a simple joke site with nodejs – Part 4 – Adding our joke routes

Wednesday, July 15th, 2015 by Phillip Napieralski

Last time, we got a basic expressjs app setup. Now, let’s bring in the stuff we created from part 2 and add to it in an expressjs way. This is the first step to awesomeness!

Adding our flat file “database” into the mix

Let’s start by building off the same app that we created in Part 3 – the happypolack auto-generated app.

Remember our JokesDB.json file from part 2? Let’s add that to the happypolack app that we created, but let’s put it in a new folder called model. Go ahead and create that folder and put the jokes json file in there:

		'category': 'chucknorris',
		'content': 'chuck norris joke'
		'category': 'yomomma',
		'content': 'momma joke'

Setting up our /jokes REST endpoints

Let’s create a new route that simply returns a simple “hello world” for our /jokes endpoints. Create the file /routes/jokes.js and add the following code:

// PART 4

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.send('GET for /jokes');
});'/', function(req, res, next) {
  res.send('POST for /jokes');

module.exports = router;

All we’re doing with this module is setting up a simple GET path and a POST path. The POST path will “eventually” be used to add a new joke to our database – where as GET path will show a listing of the jokes when your browser goes to that route.

Now, let’s make it so that going to http://localhost:3000/jokes points to this module.

To do this, let’s modify app.js (our default nodejs file). In app.js, add the following code to the top of the file:

var jokes = require('./routes/jokes');

Now, we’ve imported the jokes module. Let’s point /jokes to this module by adding the following code below the line app.use(‘/users’, users) in app.js:

app.use('/jokes', jokes);

That’s it! Now run `npm start` in the console, navigate to http://localhost:3000/jokes and you’ll see our new joke modules simple response ‘GET for /jokes’. Note, we don’t need to test the POST endpoint just yet.

Having our REST /jokes endpoint return the jokes

Bring in the file from Part 2 called database.js. Let’s put this in a new folder called /lib. This is where we’ll put all of our “helper modules”

Here’s our new database.js file so it correctly points to our jokesDB.json flat file database:

var fs = require('fs');

module.exports =
	getJokesFromDB: function()
		return fs.readFileSync('./model/jokesDB.json').toString();

With that in place, let’s modify our /jokes GET endpoint to use this module and output the jokes. Add the following line to the top of your jokes.js file to include that database module:

var db = require('../lib/database.js'); 

Then, change the router.get function to be the following:

router.get('/', function(req, res, next) {
  var jokesJson = db.getJokesFromDB();

Now CTRL+C your currently running node app and re-run `npm start`. Then, navigating to http://localhost:3000/jokes should return you the list of jokes.


That’s it! We’ve got a good start by adding our REST endpoints set-up. We’ll continue to refine the database with CRUD operations and by using MongoDB and (eventually) add in angularjs to the front-end to show the jokes on the index page in a responsive manner!

Building a simple joke site with nodejs – Part 3 – Expressjs

Thursday, June 25th, 2015 by Phillip Napieralski

A simple index-only page won’t do for a joke website. You’ll want to be able to navigate to pages that only have chuck norris jokes, or only have yo momma jokes. Or, perhaps you’ll add a page where users can submit jokes – then of course you’ll need a profile page for users. Let’s use expressjs to get our multiple pages set-up!

Auto-generating a beginning expressjs template

Let’s install express’ project generator tool, but let’s install this globally for the operating system using the -g option:

npm install express-generator -g

Let’s generate a new app called happypolack. For our template engine, we’ll use ejs. We’ll get into this more later.

express --ejs happypolack

Directories overview

Now, if you cd into the happypolack directory, you’ll see a number of different directories. There’s /public, /routes, /views and /bin. The Public directory contains everything that will actually be downloaded by your customers, such as the javascript, images and stylsheets, except for your .HTML code. Your HTML code will go into the /views folder. Though these have a .ejs extension, know that they are essentially HTML with the addition of being able to access server side code through template tags (<%= and %>). See an example of how the title is set using these template tags in /views/index.ejs.

Index, where art thou?

But, where does the title between the template tags come from? It comes from the /routes/index.js file! Let’s take a look at this code in routes/index.js:

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });

Remember in our first tutorials how you had to do “writeHead” and call “responses.end” to actually send data to the user? The way you do this in express is much different.

Let’s say, simply, that you want the web URL to show your index.ejs HTML file, and that’s it. Well, you’ll setup a route (this is index.js) and have that route included in our main app.js file (we’ll get to that). All the code in index.js is doing is setting things up so that when an HTTP GET request goes to the root of our website, it will show/render the “index[.ejs]” file and pass the variable data title.

Now, open up app.js that was generated in the root directory for you. This file is essentially our main. The top 24 lines are simple set-up that you don’t need to worry about immediately. However, let’s look at these lines of code:

var routes = require('./routes/index');
var app = express();
app.use('/', routes);

Understand this already? That route that was generated for us (routes/index.js) was simply a node module. This node module will be loaded whenever the base URL (‘/’) is navigated to by your customer (in my case I want it to be Let’s see this in action!

Lights, camera, action!

First, express included a bunch of dependencies in a package.json file. A package.json file is the main identifier for a node module. Inside of that file, there’s is an array of “dependencies” that your module requires. To install all of those dependencies, it’s easy! Type the following:

npm install

You’ll now see a bunch of new directories/modules inside a folder called node_modules.

Now run your app using either node app.js or, easier, the npm command:

npm start

By default expressjs generated apps use port 3000. Now navigate your browser to:


You should see a basic “Welcome to Express” web page. That’s it!


You’ve seen how to setup expressjs and now you should have a basic understanding of the structure expressjs creates for you. Next time, we’ll add back our basic flat file “database” and start showing some jokes!

See the rest of this tutorial series

Part 1 – Hello World
Part 2 – Adding our flat file “database”

Building a simple joke site with Nodejs – Part 2 – Reading JSON from files

Thursday, June 11th, 2015 by Phillip Napieralski

Last time we set-up NodeJS and built a simple “Hello world” app. This time, let’s have it serve up something more interesting. As a first step to building our joke website, let’s read two jokes from a file and print them out to the screen.

The “backend database” format

JSON is arguably the most widely used format to store objects with javascript. Backend databases like the document based MongoDB works seamlessly with the format. So, let’s use it!

Dump this into a file called jokesDB.json

		'category': 'chucknorris',
		'content': 'When chuck norris does a push-up, he's actually pushing the world down.'
		'category': 'yomomma',
		'content': 'Yo momma house so dirty, she has to wipe her feet before she goes outside.'

Place this file in the same directory you plan to keep your code. It will act as a temporary database from where we can retrieve our jokes.

NOTE: You probably wouldn’t want to use a flat file for a production website. Especially if you want to be able to add and remove jokes quickly from your “database.” Later on we’ll add a real database solution for which to store our data.

Our “database” module

To facilitate a clean separation later on, it makes sense to start, even now, putting our backend logic all in a separate module. You’ll thank me later when our module to interface with the database has 100s of lines of code.

Create a new file in the same directory as your jokesDB.json file and call it “database.js”. Copy this code to it:

var fs = require('fs');

module.exports =
	getJokesFromDB: function()
		return fs.readFileSync('jokesDB.json').toString();

That’s it! Now we just need to modify our server.js code.

The new server code

If you still have your code from the previous tutorial (part 1), it’ll be easy to modify the code to load the database module and show the jokes. Here’s what your new server.js file should look like:

// node modules
var http = require('http');

// our created modules
var db = require('./database');

// Handle a general user request
function handleRequest(request, response) {
	response.writeHead(200, {'Content-Type': 'text/html'});
	var jokesJson = db.getJokesFromDB();

http.createServer(handleRequest).listen(80, "");

console.log('Server running at');

Show me the jokes!

Now the magical part – let’s see what we’ve done so far. Open up a terminal/command prompt, navigate to your directory (eg; ‘cd D:\nodescripts\) and type the following:

node server.js


I showed you how to use the fs module to load in a file and output that data to a file! You’ll now see the simple file outputted to the browser when you navigate to http://localhost or (they are the same). Next time, we’ll bring expressjs in the mix to give us the ability to easily add other pages.

Building a simple joke site with nodejs – Part 1 – Hello World

Friday, May 15th, 2015 by Phillip Napieralski

If you’ve heard about nodejs and always wanted to get started with it, look no further! I’ll walk you through the basics of getting set-up and building a super simple joke website from start to finish, using my current website as a goal to get to.

NOTE: These tutorials were written with node version 0.12.4 and npm version 2.10.1. Type “node -v” and “npm -v” to see your versions

Why nodejs?

NodeJS was engineered from the ground up to be excellent at server event driven websites and services. It’s also much easier to develop in (once you get the hang of it), since you can use the same language that you use for the front-end (javascript!). Finally, the node package manager (NPM) allows you to simply and easily utilize a world of different open source and free code bases instantly!


For Windows users

Since I still use windows at home, I’m going to first walk through these instructions assuming you are running windows as well.

  1. Download the (msi) installer from the nodejs website
  2. NodeJS Website

  3. For the Install directory, I chose something a bit easier to remember:
  4. That’s it! Now, when you want to run a server, you can simply type “node .js” in your command prompt.

For Mac OS X users

A fantastic command line package manager for mac os is called brew. Once you install that, you can easily install node by simply typing:

brew install node

That’s it!

A helloworld “website”

  • Create a file called “helloworld.js” in an easy to remember directory (I chode D:\nodescripts) and add the following content to it:

    var http = require('http');
    http.createServer(function (req, res) {
    	res.writeHead(200, {'Content-Type': 'text/html'});
    	res.end('Hello World\n');
    }).listen(80, "");
    console.log('Server running at');
  • Now open up the command prompt and navigate to your file:
    cd D:\nodescripts
  • To start your local web server, now type:
    node helloworld.js
  • You should see the message

    Server running at
  • Open your browser and navigate to (also known as http://localhost)
  • Viola!


See how easy that was? Now you’re ready to get started with nodejs. Stay tuned for part 2.