Configuration of Express Application: Node.js

You may often want different settings for development environment and a different settings in the production environment. Also you could keep pushing the files to server for testing. So you’ll need to test your application in two different environments: development & production

development-production-environment-express-nodejs

In situations like this, you could have environment specific configurations using express. In this video tutorial, I’ll be walking you through setting up configurations for these environments using Express, web framework of Node.js.

Main application file
app.js

1
2
3
4
5
6
7
8
9
10
var express = require('express');
var app = express();
 
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
 
app.set('view cache', true);
// app.enable('view cache');

Here we create an express object, using which we set the configurations.
First we set the port number to whatever is set by the server – which is present in the environment variable process.env.PORT if it is not set use 3000 as port number.
Next, assign views a directory: root directory( __dirname ) and views folder. You could create any folder inside root and assign it to views. Then, set default view engine as Jade. Next we enable the view cache – btw View caching is useful in production environment.

Development Environment
app.js

1
2
3
4
// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

Here we could list all the settings needed for our development environment.

Production Environment
app.js

1
2
3
4
// production only
if ('production' == app.get('env')) {
  app.enable('view cache');
}

Here we could list all the settings needed for our production environment.

Configuring Express Application: Node.js


[youtube https://www.youtube.com/watch?v=60xRnFSMRk8]

YouTube Link: https://www.youtube.com/watch?v=60xRnFSMRk8 [Watch the Video In Full Screen.]



Note: To run with specific environment settings configuration use the following command while running your Node.js application

1
2
C:/>cd node
C:/node>NODE_ENV = production node app.js

Mixins in Jade: Node.js

Mixins in Jade are much like functions/methods in many other programming languages.

mixin-jade-express-nodejs

Basically, if you’re repeating your code at many places, you could place that code inside a mixin and replace your code with the mixin call. This would make your code cleaner and maintainable over long run.

Related Read: Loops and Conditions In Jade: Node.js

mixins in Jade
mixin.jade

1
2
3
4
mixin fetch(users)
 ul
 -each user in users
  li= user

This would get the users as argument – loop through each user and put the individual user in the list item of an unordered list.

include in index file: Jade
index.jade

1
2
3
4
5
6
7
8
9
include mixin
 
- users = ["Apple", "IBM"];
mixin fetch(users)
 
<br /><br />
 
- users = ["Google", "Amazon"];
mixin fetch(users)

Here we have included the mixin.jade file, and now use our fetch mixin and pass-in our array variable, which is converted into an unordered list of items and output on the browser.

Mixins in Jade: Node.js


[youtube https://www.youtube.com/watch?v=g6DPkVpfauc]

YouTube Link: https://www.youtube.com/watch?v=g6DPkVpfauc [Watch the Video In Full Screen.]



Note: Clearly, in real-time applications the array or object come from the database.
Example: You might encounter the situation to list out all the users in your list and list of all the participating companies. Or list of all companies someone has worked at. In such cases you’ll get an array of objects which you need to out put to the user in a well formatted manner. In situations like this, mixins are a great tool to have, to avoid the necesity to repeat your code allover your application.

Have all your mixins in a single file and then include that file wherever you are calling your mixins.

Loops and Conditions In Jade: Node.js

After going through the basics of Jade, lets learn about loops and conditional statements in Jade.

loops-and-conditions-in-jade-nodejs

Note: Since most text editors designed for web remove the indentation(and some retain only new line characters), thus compressing the file and optimizing it for the web use. But this doesn’t serve any good for writing Jade. Because indentation is at the heart of Jade syntax!

So in this tutorial, we are using a Chrome extension called Jade Editor to illustrate loops and conditional statements. You can simply test your code in this Google Chrome extension and then copy over the code to your actual file. This would even help reduce the complicated errors in lengthy files.

each loop in Jade
arrays

1
2
3
4
5
- names = ["Apple", "Microsoft", "Oracle"];
 
ul
each name in names
  li #{name}

output

  • Apple
  • Microsoft
  • Oracle

sign is optional for each loop. Here it loops through the array names and prints out each element of the array.

each loop and loop index in Jade
arrays

1
2
3
4
5
- names = ["Apple", "Microsoft", "Oracle"];
 
ul
each name, i in names
  li #{i+1}: #{name}

output

  • 1: Apple
  • 2: Microsoft
  • 3: Oracle

This prints out name along with the index number. Since index in JavaScript array starts with 0, we add 1 to it, to make it more sensible for non-programmers.

for loop and loop index in Jade
arrays

1
2
3
4
5
- names = ["Apple", "Microsoft", "Oracle"];
 
ul
for name, i in names
  li #{i+1}: #{name}

output

  • 1: Apple
  • 2: Microsoft
  • 3: Oracle

Same holds good even for for loop.

each loop in Jade
objects: Key, Value pair

1
2
3
4
5
- obj = {cmp1: "Apple", cmp2: "IBM"};
 
ul
each val, key in obj
  li #{key}: #{val}

output

  • cmp1: Apple
  • cmp2: IBM

Since objects in JavaScript has {key: value} pair, we make use of it to extract and print from the object.

for loop in Jade
objects: Key, Value pair

1
2
3
4
5
- obj = {cmp1: "Apple", cmp2: "IBM"};
 
ul
for val, key in obj
  li #{key}: #{val}

output

  • cmp1: Apple
  • cmp2: IBM

Same holds good to for loop too.

Conditional Statements

if, else if, else In Jade
Conditional Statements

1
2
3
4
5
6
7
8
- var fc = 2;
 
if( fc === 0 )
 p You have no followers
else if( fc === 1 )
 p You have 1 follower
else
 p You have #{fc} followers

output
You have 2 followers

Here we use the condition to check for execution of block of code. Also note that sign before if, else if and else keywords are optional.

Loops and Conditions In Jade: Node.js


[youtube https://www.youtube.com/watch?v=wL60uzhwwTA]

YouTube Link: https://www.youtube.com/watch?v=wL60uzhwwTA [Watch the Video In Full Screen.]



In coming video tutorials, we shall learn about Mixins.

Basics of Jade – Template Engine: Node.js

Lets learn some of the basics of Jade Template Engine. Jade is the default template engine for Express Web Framework of Node.js Also note that, Jade and Express are open source product of the same company, so go very well with each other!

jade-template-engine-nodejs-express-web-framework

Using template engine might seem pointless in the beginning, but if you’re building a large-scale application, it’s a handy tool and you’ll feel good about your decision to use one for your project.

Make sure you’ve installed Express Web framework and Jade module locally for your application. You can find the procedure at Express Web Framework: Node.js

Configuration Section
app.js

1
app.set('view engine', 'jade');

This would let your application know that you’ll be using Jade as Template Engine. This way, you need not mention the Template Engines file extension each time.

Jade File: Indentation
index.jade

1
2
3
4
html
 head
  title Technotip
 body

Would output

1
2
3
4
5
<html>
 <head><title>Technotip</title></head>
 <body>
 </body>
</html>

Indentations in Jade decide which element(s) is/are a child off which element.

Jade File: Variable
index.jade

1
2
 - var name = "Love For Design"
 p= name

and

Jade File: String. Minus sign significance
index.jade

1
2
 - var name = "Love For Design"
 p #{name}

Out put Love For Design on the browser, inside a paragraph tag.

Jade File: Code Interpretation – REPL
index.jade

1
 p #{ 1 + 5 }

This outputs 6 on to the browser inside a paragraph tag.

Jade File: String Length Management
index.jade

1
2
3
4
5
6
7
 p
  | My Name is Satish
  | I Love web development
  | I love helping people
  | by teaching them whatever I know
  | I believe, this is a good cause of 
  | spreading knowledge.

This would treat the entire string as a single line text, and out put looks like:
My Name is Satish I Love web development I love helping people by teaching them whatever I know I believe, this is a good cause of spreading knowledge.

Jade File: Id’s and Classes
index.jade

1
2
div#wrapper
  p.highlight I Love Node.js

This would apply the id wrapper to div and highlight class to p tag.

Jade File: Multiple id and class
index.jade

1
2
div#wrapper.content.highlight
  p I Love Node.js

We could even assign multiple id’s and classes to a html element.

Jade File: Anchor Tag
index.jade

1
a(href="/about", rel="nofollow") Satish

This would wrap the word Satish with anchor tag and nofollow attribute.

Jade File: Anchor Tag and Image Tag
index.jade

1
2
a(href="/about", rel="nofollow") Satish
img(src="1.gif", alt="Child Eating KitKat")

This would output Satish with anchor tag and nofollow attribute. Also an image with alt attribute attached to it. Both these tags are siblings.

Jade File: Hyperlink the Image file – Hypermedia
index.jade

1
2
a(href="/about", rel="nofollow")
 img(src="1.gif", alt="Child Eating KitKat")

Indent img tag inside anchor tag and the image gets linked to by the anchor tag.

Jade File: Writing Function inside Jade file
index.jade

1
2
- var fn = function() { return "android KitKat"}
p #{fn()}

This outputs android KitKat to the browser.

Jade File: Accessing elements of Object
index.jade

1
2
3
4
- obj = { name: "Apple", product: "iPhone"}
ul
  li #{obj.name}
  li #{obj.product}

This would output

  • Apple
  • iPhone

Jade File: Accessing elements of an array
index.jade

1
2
3
4
- obj = [ "Nexus 5", "iPhone 5S"]
ul
  li #{obj[0]}
  li #{obj[1]}

This would output

  • Nexus 5
  • iPhone 5S

Jade File: Including another jade file
index.jade

1
2
p
 include show

This would include the contents of show.jade file inside index.jade file.

Basics of Jade – Template Engine: Node.js


[youtube https://www.youtube.com/watch?v=xNoWTLsZbaU]

YouTube Link: https://www.youtube.com/watch?v=xNoWTLsZbaU [Watch the Video In Full Screen.]



Note:
sign tells jade that the code that follows should be executed.
= sign tells that the code should be evaluated, escaped and then output.

Stay subscribed: In next video we’ll show how to use bootstrap + Express + Jade + Node.js
Building a web form. Loops and Conditional statements present in Jade.

Auto Restart Server With NoDemon: Node.js

As we have already started using Web Framework of Node.js i.e., Express, we’ll be building considerably large web applications, and it needs us to edit the files often. We need to restart the server every time we save changes to main application file. This would start consuming lot of time and sometimes we may forget to restart the server and may think that our application file has bugs, as it doesn’t reflect on the browser!

node-server-auto-restart

To solve this issue, we could make use of some dependency modules which listens to the changes we saved to these main node application file and restarts the server automatically by itself.

Package File
package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "name": "route-app",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "3.4.0",
    "jade": "*",
    "nodemon": "*"
  }
}

As you can see we have added nodemon as a dependency to our application.

Local Module Installation
installation of dependencies

1
npm install

This installs all the dependencies listed in package.json file. If some of the dependencies are already installed, it ignores such things and installs the new dependencies listed in package.json file.

1
nodemon app.js

Since NoDemon is a local module to our application, you can not execute your node application using above command. However there is a simple work around for this:

Change starting point of execution
package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "name": "route-app",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "nodemon app.js"
  },
  "dependencies": {
    "express": "3.4.0",
    "jade": "*",
    "nodemon": "*"
  }
}

In above file we change the value of start from node app.js to nodemon app.js

Execution Command
Command Prompt / Console

1
npm start

Now this command would trigger the nodemon app.js present inside package.json file, which is local to our specific application.

Auto Restart Server With NoDemon: Node.js


[youtube https://www.youtube.com/watch?v=eMZZa1nh8iY]

YouTube Link: https://www.youtube.com/watch?v=eMZZa1nh8iY [Watch the Video In Full Screen.]



Now whenever we make changes to app.js file, and hit save, nodemon object listens to the new changes we saved, and restarts the server. This way we save a lot of time while in development mode, and directly see the changes reflect on our web browser almost immediately upon refreshing the web browser.

Note: Changes to files in public directory and the .jade files doesn’t require a server restart to reflect on the browser. These are files which are simply rendered upon calling, so whatever is present in these files are [compiled and] shown whenever there is a request to it.