In this video tutorial we shall briefly look at Express web framework for Node.js
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
extends layout
block content
h1= title
p Welcome to #{title}
This jade file is present inside view folder.
More about Jade Template Engine in coming videos ..
Note:
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!
Using Node.js application we’ll check if a website is up and running or is it down.
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);
});
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]);
});
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.
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.
Lets learn how to Create, read and write a file using file server module of Node.js
In this video tutorial we shall learn creating a folder/directory, creating a file, reading from a file, writing to a file and copying content from one file to another. We shall also see how you can look at all other facilities provided by fs module and make use of it in your real-time node.js web applications.
JavaScript: Reading a file app.js
1
2
3
4
5
var fs= require("fs");
var html= fs.readFileSync("index.html", "UTF-8");
console.log(html);
var fs= require("fs");
var html= fs.readFileSync("index.html", "UTF-8");
console.log(html);
Here we require fs module of node.js Using the readFileSync method of fs object, we open and read the file presented to it as its first argument. Second argument is the character-set type.
HTML FILE index.html
1
2
3
<html>
<h1>Technotip.com</h1>
</html>
<html>
<h1>Technotip.com</h1>
</html>
This is the html source code which will be fetched by app.js and being displayed on the console window upon execution.
JavaScript: Creating New File and Writing to file app.js
1
2
3
4
var fs= require("fs");
var html= fs.readFileSync("index.html", "UTF-8");
fs.writeFileSync("satish.html", html);
var fs= require("fs");
var html= fs.readFileSync("index.html", "UTF-8");
fs.writeFileSync("satish.html", html);
Here we pass 2 arguments to writeFileSync method. First parameter being the file name – to be created, and the second parameter contains the content to be copied to the file we created.
JavaScript: Creating Directory/folder app.js
1
2
3
4
5
var fs= require("fs");
fs.mkdir("satish");
console.log("Folder created!");
var fs= require("fs");
fs.mkdir("satish");
console.log("Folder created!");
Pass name of the folder to be created to mkdir method of fs object.
JavaScript: Deleting a file app.js
1
2
3
4
var fs= require("fs");
fs.unlink("satish.html");
console.log("File deleted");
var fs= require("fs");
fs.unlink("satish.html");
console.log("File deleted");
Pass the existing file name to the unlink method and it’ll delete it. Make sure to give proper file name with correct file extension and path.
Note: There are plenty other file operation facilities provided by fs module, please use some other properties and methods from below list and let us know the code and what it does in the comment section below. This would surely help everyone in our reader community.
With this video tutorial, lets learn about testing our code snippets using REPL, before implementing it into the actual node application. And then, we’ll show you how to add routes to your node server.
In this tutorial, we create 5 routes to the server: “/” to “Home Page” “/about” to “About Us” “/contact” to “Contact Us” /”satish” redirected to “Home Page” anything else to “Page Not Found”
Here we test our code snippets on the command prompt, before implementing it into our actual application. Working with node url module on command prompt, we learnt to make use of parse() method of url object to fetch the hostname, port and the pathname of the actual URL. We are interested in pathname – we’ll be using it in our node application.
Here we require url and http module. Using http object we create HTTP Server. Using url object we call parse method to parse and fetch the path from the user request URL.
Once we fetch the path, using conditional statements we display the corresponding message with appropriate response header information. We also illustrate 301 redirection
C:\>node
> 1 + 1
2
> var a;
undefined
> a = 10
10
> a + 5
15
> a
10
> ++a
11
> a++
11
> a
12
> "Satish "+"B"
'Satish B'
> function technotip() { return 101; }
undefined
> technotip();
101
>2
C:\>node
> 1 + 1
2
> var a;
undefined
> a = 10
10
> a + 5
15
> a
10
> ++a
11
> a++
11
> a
12
> "Satish "+"B"
'Satish B'
> function technotip() { return 101; }
undefined
> technotip();
101
>2
Here we can type in our valid code snippet and instantly get the results. Some of the things we can do are: arithmetic operations, string manipulations, pre and post increment decrement of numbers, method declaration and defining and calling the methods etc.
We could even require some built-in node modules and using its objects we can look at the methods and properties it provides. Command Prompt Console Window
Note: Node.js is built on the same Google’s V8 JavaScript Engine which is using by Google’s Chrome – thus providing the same speed and robustness to our node.js applications.