Node JS – Building with express – part 1

Express is a web application framework for node. Its certainly the most popular one in the node web ecosystem. Lets install it using npm. With npm you can install in 2 ways – globally (so that they are available to every project inside your system) and project to project basis.  You can install it globally by the following command :


npm install -g express

Above will install the latest version of express. If you want any specific version then just specify the same at the end. Typically in a nodejs app we have a package.json file that contain information about our node application.  lets make one by using ‘npm init’

express-demo1-npm_init

Most of the parameters are pretty obvious, the ‘entry point’ is the name of the file where you application starts. Now use express you need to add express dependencies to this file. Again we can type in manually or excute the following command to do it for us. Run the following in the folder where your package.json is


npm install express --save

This will add a folder in your project folder node_modules having express files and also edit the package.json file to inculde the dependencies.  Lets create app.js


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

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

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});

run it using node app.js

The app starts a server and listens on port 3000 for connection. It will respond with “Hello World!” for requests to the root URL (/) or route. For every other path, it will respond with a 404 Not Found. As you can guess , we can map different url and map it so as to send out a different response.
We can also pass information through our routes to our application using parameters. Add the following code:


app.get('/hello/:name?', function (req, res) {
  var name=req.params.name;
  res.send('Hello ' + name+ '!!');
});

Above we pass in the name parameter from the url to the application which was added in the response. Note that you have to restart your node app again. This needs to be done after every change made to the code.

So far we have been creating content using the ‘send’ method. Express allows us to use templating engine that will make this easy. By default express uses ‘jade’ templating engine. But if you are coming from writng jsp/html background its a little bit difficult to get use to. You can use a different templating engine called ‘EJS’ – embedded javascript. To install just go to your command prompt inside of your project and type


npm install ejs --save

If you check your package.json file you will find a new dependency of EJS. By default, ejs assumes a views folder to be present where all our ejs files would be. So lets make a folder views inside our app and make a index.js with some html in it

express-demo1-ejs

Now you have to specify express that you are using ejs as the templating engine. Lets change the app.js


var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
  res.render('index');
});
var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log('Example app listening at http://%s:%s', host, port);
});

Notice that in render method you do not have to mention the ‘views’ folder name as it expects all templates to it by default. If you want your own folder name you could use : app.set(‘views’, __dirname+’/public’); or whatever you want it name to be. ‘__dir’ gives the path to project root. Lets test by restarting application.

You can pass along some data to your ejs template by sending upon extra objects to your render method. LEts change the in app.js


app.get('/', function (req, res) {
  res.render('index',{
      title:'List of Users',
      users:['User1','User2','User3']
  });
});

Capturing above js object in out index.ejs


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
 <title>Demo 1 - EJS</title>
</head>
<body>
<H1><%= title%></H1>
<% for(var i=0; i<users.length; i++){ %>
<li> <%= users[i]%> 
<% } %>
</body>
</html>

In EJS you can print data we use <%= your data %> and is you want to use js you can use <% your js %>. Lets restart and see

express-demo1-ejs2

Lets modularize our code by seperating our routes into a different file and using partials for header and footers.

express_partials

Changing the index.ejs


<!DOCTYPE html>
<html>
<head>
  <% include  partials/header.ejs %>
</head>
<body>
<H1><%= title%></H1>
<% for(var i=0; i<users.length; i++){ %>
<li> <%= users[i]%>
<% } %>
</body>
<%include  partials/footer.ejs %>
</html>

Notice since the default path for ejs is views folder , we have to give the path relative to that.
Lets move our routes code to a differnt file called routes.js


exports.users= function (req, res) {
res.render('index',{
title:'List of Users',
users:['User1','User2','User3']
});
}

exports.home= function (req, res) {
res.send("Home Page");
}

Changing app.js


var express = require('express');
var routes = require('./routes.js');
var app = express();
app.set('view engine', 'ejs');

app.get('/users', routes.users);

app.get('/', routes.home);

var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;

console.log('Example app listening at http://%s:%s', host, port);
});

This way code is more modularize and easy to maintain. Thats it for now. Next we will se how to use express generator.

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: