Build Web Apps with the Express Framework
Built on the Node.js platform, Express is a minimal and flexible Web application framework that provides a strong set of features for building single, multi-page and hybrid Web applications. Here is a step-by-step guide that leads readers through installi
Express.js is the popular Web application framework for the Node environment. It helps developers with simple, yet powerful capabilities that augment Node. Node.js has established itself as a robust environment for developing complex server-based software. One such application is Web development. 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 functionality 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 programming capability as an API, it also provides skeleton programmes (templates) to start your applications. It even has sufficient options to choose the extensions or libraries that you are comfortable 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 understanding 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 application), req (request) and res (response). The object app is used for application 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 functionality performed between the request received from the browser and the response sent back to browser is the function of middleware. The functionalities 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 applications such as blogging sites and e-commerce sites. Express, by itself, does not impose any restrictions on how you use the framework or build your project structure. It offers complete flexibility 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 capabilities towards the HTML pages and CSS. Jade has programming constructs such as looping, variables, etc, which make for the generation of Web pages, but an introduction to Jade is not within the scope of this article.
Installation 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 ‘photoviewer’:
$ express photoviewer create : photoviewer create : photoviewer/package.json create : photoviewer/app.js create : photoviewer/public create : photoviewer/routes create : photoviewer/routes/index.js create : photoviewer/routes/user.js create : photoviewer/views create : photoviewer/views/layout.jade create : photoviewer/views/index.jade create : photoviewer/public/stylesheets create : photoviewer/public/stylesheets/style.css create : photoviewer/public/javascripts create : photoviewer/public/images
Install dependencies, as shown below:
$ cd photoviewer && npm install
Run the app, as follows:
$ node app $ cd photoviewer $ 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 stylesheets, 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.
Photoviewer
Now, let’s host a photoviewer 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 photoviewer/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 dependencies. 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: Photoviewer
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.createServer(app).listen(app.get('port'),
function(){
25 console.log('Photo viewer started at http://localhost:' + app.get('port')); 26 }); Here is the explanation for the code given above. Lines 5 - 8: Initialises objects from their respective node modules of Express, routes, http and path. Express is the main object that allows the setting of application 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 application, for setting the attributes and using middleware functionality.
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 extensibility. 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 photoviewer/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',
{ followLinks: 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 explanation 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 encountered.
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 photoviewer/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='/stylesheets/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 explanation 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 programmers 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 photoviewer project
To enhance the photoviewer project, it is recommended that you learn the Jade Template language. Jade is easy to code due to its shorthand notation and the powerful embedding of programming 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 photoviewer functionality 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=eD2I0zAjM5g [3] Tutorial on Express.js explaining connect and routes-http:// evanhahn.com/understanding-express-js/ [4] Introduction to middleware- http://stephensugden.com/
middleware_guide/ The author is passionate about Web technologies and has a growing interest in JavaScript frameworks and Node environments. He is currently working for HP, Bengaluru.