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.

Express Web Framework: Node.js

In this video tutorial we shall briefly look at Express web framework for Node.js

express-modules-file-structure-nodejs

With today’s tutorial we will be discussing the basics of Express and we’ll also be running a small example application built with Express, also we shall have a first look at Jade Template Engine.

REPL
global installation of Express Framework

C:\>npm install -g express

This installs the express globally, so that you can access it from anywhere in the system.

Also note that, you’ll need internet connection to download and install these packages.

REPL
creating express example application

C:\>cd node
C:\node>express express_example

This creates a folder and some recommended folder structure. If you’re a total beginner to Express Framework, then it’s better to stick on with these folder structure.

Now open the package.json present inside express_example folder
JSON File
package.json

{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "3.4.0",
    "jade": "*"
  }
}

It looks as shown above. It has 2 dependencies: express and jade. Install these dependencies from your command prompt / console.

REPL
installing dependencies

C:\>cd node
C:\node>cd express_example
C:\node\express_example>nmp install

This would install both express and jade, and another folder called node_modules gets created inside express_example folder.


 express-jade-modules-nodejs

Video Tutorials: Getting Started With Express Web Framework: Node.js


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

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



Jade File
Jade to HTML

extends layout

block content
  h1= title
  p Welcome to #{title}

This jade file is present inside view folder.

jade-to-html-express-node

More about Jade Template Engine in coming videos ..

Note:


express-modules-file-structure-nodejs

Inside node_modules folder we have dependency modules.
Inside public folder javascript files, css files, images etc are present. Logical part of the application will be kept separate for security reasons.
Inside routes, routing configuration is present.
Inside views, the presentation part of the application is present. If Template Engine is used, those files will be present in this folder. Example: .jade files

app.js Starting point of execution.
package.json Contains app name, version, author, dependency module names etc.

Info: There are many popular websites built upon Express Framework, one that you might know is, MySpace!

Server Up or Down: Node.js

Using Node.js application we’ll check if a website is up and running or is it down.

check-website-up-or-down-nodejs

This is a simple application which pings server/URL and checks for the returned status code. Depending upon the status code returned, it displays message to the user on the console window.

JavaScript: Checking for status code
app.js

1
2
3
4
5
6
7
8
var http = require("http");
 
     http.get({host: "technotip.org"}, function(res){
    if( res.statusCode == 200 )
   console.log("This site is up and running!");
 else
   console.log("This site might be down "+res.statusCode);
   });

Here get() method of http object takes 2 parameters. First parameter is an object which contains host name, and the second parameter is a callback method, which gets its parameter from get() methods first parameter.

Using the res object we fetch the status code returned by the server. If the status code is 200, it means website is up and running. Else the website might be down.

Some times we get status code other than 200 and the site will still be up and running, in such cases we can display user-friendly messages and not web geek status codes!

JavaScript: Checking If website is Up or Down
app.js

1
2
3
4
5
6
7
8
9
10
11
var http = require("http");
 
 
  http.get({host: "www.technotip.org"}, function(res){
    if( res.statusCode == 200 || res.statusCode == 301 )
   console.log("Website Up and Running ..")
 else
  console.log("Website down");
 
console.log(http.STATUS_CODES[res.statusCode]);
   });

http object has yet another object nested inside it, called STATUS_CODES which has a list of status codes and its corresponding meaning: as key value pairs. Using this, we could fetch the description of the status code and display it to the user, which will be much more meaningful.

Check if the Server is Up or Down: Node.js


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

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



Note: If we implement this as a web application, users could check if the website is down for everyone or is it just them.

You could even go through the entire list of all the status codes and implement a complete check and return the result to the user and not let the user guessing with the status code meaning.