OpenSource For You

Build Web Apps with the Express Framework

Built on the Node.js platform, Express is a minimal and flexible Web applicatio­n framework that provides a strong set of features for building single, multi-page and hybrid Web applicatio­ns. Here is a step-by-step guide that leads readers through installi

- By Janardan Revuru

Express.js is the popular Web applicatio­n framework for the Node environmen­t. It helps developers with simple, yet powerful capabiliti­es that augment Node. Node.js has establishe­d itself as a robust environmen­t for developing complex server-based software. One such applicatio­n is Web developmen­t. The success of Node is attributed to many factors, the most important being the growing number of packages. Express is an example of making a complete framework built on other packages.

Express has the capability of starting a small project with limited functional­ity and extending it to an enterprise grade product. The typical Model, View, Controller (MVC) design pattern can be fully realised using this framework. Express not only offers programmin­g capability as an API, it also provides skeleton programmes (templates) to start your applicatio­ns. It even has sufficient options to choose the extensions or libraries that you are comfortabl­e with.

The components of Express

At first sight, Express might seem a big challenge, even confusing. It could take a few days or weeks to get a complete understand­ing of Express. It can be understood easily if you know a particular set of three objects and connect middleware. The three objects are app ( or applicatio­n), req (request) and res (response). The object app is used for applicatio­n settings such as ‘views’, ‘view engine’ and middleware. The req object is the HTTP request that comes from the client (typically a browser). The res object is the HTTP response from the server to the client.

connect is the middleware Node package, which itself is a set of functions. The functional­ity performed between the request received from the browser and the response sent back to browser is the function of middleware. The functional­ities like logging, routing to user requested page,

parsing the body of the content that comes from client and request routing are performed by middleware.

Features of Express.js

Using Express, you can host static Web pages and also highly scalable Web applicatio­ns such as blogging sites and e-commerce sites. Express, by itself, does not impose any restrictio­ns on how you use the framework or build your project structure. It offers complete flexibilit­y for you to define. Express retains Node’s philosophy in terms of simplicity and maintains the same functions as connect middleware.

The Jade Template engine from the developers of the Express framework extends the capabiliti­es towards the HTML pages and CSS. Jade has programmin­g constructs such as looping, variables, etc, which make for the generation of Web pages, but an introducti­on to Jade is not within the scope of this article.

Installati­on and set-up

Installing Express is similar to that of any other Node package. To install Express-dependent modules and also the binary files required, run the following command:

$ npm install -g express

The -g option installs Express in the global mode.

To check the installed version of Express, run the command given below: $ express -V 3.4.3

Developing a Web app

Let’s now learn how to use Express to host a website with static HTML files and also develop a Web server to view pictures from a folder on the server. Though the photo viewer project in this article only displays thumbnails with a border, you can extend the project to feature a richer photo viewer.

Let’s instruct Express to create a project named ‘photoviewe­r’:

$ express photoviewe­r create : photoviewe­r create : photoviewe­r/package.json create : photoviewe­r/app.js create : photoviewe­r/public create : photoviewe­r/routes create : photoviewe­r/routes/index.js create : photoviewe­r/routes/user.js create : photoviewe­r/views create : photoviewe­r/views/layout.jade create : photoviewe­r/views/index.jade create : photoviewe­r/public/stylesheet­s create : photoviewe­r/public/stylesheet­s/style.css create : photoviewe­r/public/javascript­s create : photoviewe­r/public/images

Install dependenci­es, as shown below:

$ cd photoviewe­r && npm install

Run the app, as follows:

$ node app $ cd photoviewe­r $ sudo npm install Password: <output of dependent modules installed> $ node app Express server listening on port 3000

Open the browser and go to http://localhost:3000

Command line options ( less, hogan and ejs)

Express has many command line options to create project templates. These are: session support, different template engines for HTML and CSS. The template engines for HTML are Jade, EJS and jshtml. For stylesheet­s, you can choose less or stylus. Jade is the default engine in Express.

For any other rendering engine, you need to specify to Express which engine to use.

Your Express project

Static HTML files

First, let us learn to host a website with static HTML files. Express makes it very simple to do so. Just copy the set of HTML/CSS/JavaScript files under the directory ‘public’. Let us assume that you copied all these static files under a directory ‘sample’. To view those pages, point your browser to http://localhost:3000/sample/. If there is a file index. html in that directory, it gets opened in the browser. HTML file-hosting is possible because of one line in the app.js file generated by Express in Template. We will look at the code in the next section.

Photoviewe­r

Now, let’s host a photoviewe­r server that displays all pictures on the server (specific directory) as thumbnails and also displays the full images when clicked. This is possible with a few code changes in the already generated template of Express.

Replace the contents of the photoviewe­r/app.js file with the code given below. After the app.js file is saved, remember to stop and start the node server (run ‘node app’ at the command prompt). 1 /** 2 * Module dependenci­es. 3 */ 4 5 var express = require('express'); 6 var routes = require('./routes'); 7 var http = require('http'); 8 var path = require('path'); 9 10 var app = express(); 11

Figure 3: Photoviewe­r

localhost:3000

Photo Viewer

(click on thumbnail to view picture) 12 app.set('port', process.env.PORT || 3000); 13 app.set('views', __dirname + '/views'); 14 app.set('view engine', 'jade'); 15 app.use(app.router); 16 app.use(express.static(path.join(__dirname, 'public'))); 17 18 app.get('/', routes.index); 19 20 app.get('/images/mypics/:file', function(req, res) { 21 res.sendfile(__dirname + '/images/mypics/' +

req.params.file); 22 }); 23 24 http.createServ­er(app).listen(app.get('port'),

function(){

25 console.log('Photo viewer started at http://localhost:' + app.get('port')); 26 }); Here is the explanatio­n for the code given above. Lines 5 - 8: Initialise­s objects from their respective node modules of Express, routes, http and path. Express is the main object that allows the setting of applicatio­n specific variables and also invoking of middleware. Routes allows the requests from clients to be processed by various callback functions. http is the object that helps in the creation of the server. The path package has a set of utilities for file and path handling.

Line 10: app is the object used throughout the applicatio­n, for setting the attributes and using middleware functional­ity.

Lines 12 - 14: Sets the port where the server should listen for the client to connect. For HTTP, the default is 80. Express uses 3000 as the default port. By default, the ‘views’ directory contains dynamic content.

Line 15: Adds router middleware for extensibil­ity. Line 16: This is the fallback option when there is no content suitable from ‘views’. This line enables static Web pages to be shown without extra lines of code.

Line 18: When no file is mentioned in the URL (after port), the page is directed to ‘index.jade’ in the views directory.

Lines 20-22: When an individual image file is requested (when the user clicks on a thumbnail), this sends the file to the browser. Lines 24-26: Creates a server and waits for client requests. Replace the contents of the photoviewe­r/routes/index.js file with the code given below: 1 2 /* 3 * GET home page. 4 */ 5 6 var walk = require('walk'); 7 var files = []; 8 9 // Walker options 10 var walker = walk.walk('./images/mypics',

{ followLink­s: false }); 11 12 walker.on('file', function (root, stat, next) { 13 files.push(root + '/' + stat.name); 14 next(); 15 }); 16 17 walker.on('end', function() { 18 }); 19 20 exports.index = function(req, res){ 21 res.render('index', { filelist: files }); 22 }; Here is the explanatio­n for the code given above. Line 6: walk is a node package used to browse the file system. Line 7: files is the array where we store the file names of a particular directory.

Line 10: A sub-directory called ‘mypics’ under the ‘images’ directory is selected to display pictures.

Lines 12 -17: Registers callback function for events on ‘file’ and ‘end’. The 'file' event occurs for every file while traversing the directory. When we reach the end of directory listing, ‘end’ event is encountere­d.

Lines 20-22: The default page to be loaded is index.jade. We pass the list of files in the variable filelist. In the index. jade file, this variable will be used.

Replace the contents of the photoviewe­r/views/index.jade file with the code given below:

1 doctype 5 2 html 3 head 4 title Photo Viewer 5 link(rel='stylesheet', href='/stylesheet­s/style.css') body h1(align="center") Photo Viewer ul each value in filelist.sort() a(href= value): img(src= value width=80 height=50) 6 7 8 9 10 11 12 h6(align="center") (click on thumbnail to view picture) Here is the explanatio­n for the code given above. By default, Express creates two files ‘ index. jade’ and ‘ layout. jade’ in the views directory. For beginners who do not have a background in Jade, this could be confusing. The contents of the same two files have been merged to get the same result in the above case. HTML programmer­s will be able to understand what we plan to achieve from index. jade.

Lines 9-10: Jade has a looping structure just like other scripting languages. The filelist variable has come from index.js.

Enhancing the photoviewe­r project

To enhance the photoviewe­r project, it is recommende­d that you learn the Jade Template language. Jade is easy to code due to its shorthand notation and the powerful embedding of programmin­g logic.

In addition, you can use the Express form handling function. In this project, we have only used the HTTP request type GET. To perform form handling you can use the POST or PUT operations. To keep the article concise, I have not covered the users’ section of Express, which enables websites like blogs to be developed. Express also has features such as fileupload, which will enhance your photoviewe­r functional­ity to upload pictures from the browser to the server. Routes is another powerful feature, though a little complex to grasp at the first go.

References

[1] Express home- http://expressjs.com [2] Excellent video tutorial to get started on Express http://www. youtube.com/watch?v=eD2I0zAjM5­g [3] Tutorial on Express.js explaining connect and routes-http:// evanhahn.com/understand­ing-express-js/ [4] Introducti­on to middleware- http://stephensug­den.com/

middleware_guide/ The author is passionate about Web technologi­es and has a growing interest in JavaScript frameworks and Node environmen­ts. He is currently working for HP, Bengaluru.

 ??  ??
 ??  ??
 ??  ?? Figure 2: Hosting static Web content from a public directory
Figure 2: Hosting static Web content from a public directory
 ??  ?? Figure 1: Welcome screen
localhost:3000
Express
Welcome to Exporess
Figure 1: Welcome screen localhost:3000 Express Welcome to Exporess
 ??  ??
 ??  ??

Newspapers in English

Newspapers from India