3 Best Web Frameworks For NodeJS, Part I: ExpressJS

Prologue

I highly recommend reading the following articles before you get into this article. The following articles provide you the details of the internals and how to get started with NodeJS.

As we know, NodeJS is a platform to create fast and scalable network applications; we have seen a simple web server using NodeJS. But in that example, we just used NodeJS's native modules to create a web server application.

But we have many frameworks to help create network applications quickly and that provide easy ways to get the same functionalities with less time. Of those frameworks, I am exploring 3 three.

In this article, we will discuss one of the senior frameworks, “ExpressJS”.

ExpressJS

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications, from expressjs.com.

We can develop single-page apps as well as multi-page applications using the ExpressJS framework. ExpressJS is designed for providing fundamental web application features, on top of NodeJS features.

ExpressJS can be downloaded using the NPM. To create an example web server, setup the project environment as shown in my previous article.

Installing ExpressJS

To install the ExpressJS framework, type the following command in the Node CLI.

> npm install –g express.

The preceding command will install the express in the global node modules folder. If you avoid using the –g option, the express framework will be installed only on the local folder (project root folder).

Express Generator

The quickest way to create an express applications architecture is to install the express-generator. Execute the following command in node's CLI to create the express application folders and default files required.

> npm install –g express-generator@4

The preceding line will install the generator in the global folder. Now to create the express application folder structures and required files, just execute the following commands:

> express

npm install

In the preceding figure, the express command created the folder and the files as required. Now to install the dependencies, use the npm install command to install all the dependencies given in the package.json file.

But in our example, we are not going to use the generator to create our application structure, instead we will create each and every file ourselves when it is required.

First, we will create a simple web server using express. For that, we just add a JavaScript file with the name “app.js” under the root folder and copy and paste the following code.

  1. var express = require('express'); // requires express framework module into express variable.  
  2. var app = express(); // creating new express app.  
  3. app.get('/', function(req, res){ // callback to be executed whenever a request comes.   
  4.   res.send('hello world'); // sending response to the client.  
  5. });  
  6. app.listen(3000, ‘127.0.0.1’); // listening on the port & host.  
In the code above, we are creating an express application that listens on the port 3000 and IP "127.0.0.1". When a request comes, the callback bound with app.get will be executed.

Express Settings

We can set and get the setting for Express applications using the app.set and app.get methods. The following are some of the frequently used setting values. 
  • app.set(‘env’, ‘development’): the "env’ setting value can be used to detect the environment mode.

  • app.set(‘view cache’, true): if the view cache value is true, then the templates are cached. In the production environment, the templates are cached.

  • app.set(‘view engine’, ‘jade’): The view engine to be used to compile the view. If you omit it, the default view engine will used.

  • app.set(‘views, ‘/views’): used to set the view path.
We can enable/disable the settings using the following functions.
  • app.enable(‘view cache’); app.disable(‘view cache’).

  • To check whether some of the settings are enabled or disabled, we could use app.enabled(‘setting name’) and app.disabled(‘setting name’).

Middlewares in ExpressJS (the use of app.use)

Middlewares are sets of code to be executed for every request on the given path (the default path is "/") in the order they have mounted with the express app.

The path can be a string representing a path, a path pattern, a regular expression to match paths, or an array of combinations of the aforementioned path objects.

The middlewares could be mounted as single, array of middlewares or combination of single and array of middlewares.

There are the following four type of Middlewares available in Express:

  • Application Level (app.use(/*…. */))
  • Router Level (route.use(/*…. */))
  • Third-party (cookie-parser)
  • Built-in (express.static)

For example:

  1. // this middleware will be executed for every request to the app  
  2. app.use(function (req, res, next) {  
  3.   console.log('Date & Time: %d', Date.now());  
  4.   next(); // continues with the next middleware  
  5. });  
In the code above, a simple single middleware is to be executed whenever a request comes in.

There are many builtin middlewares available in the ExpressJS. The middleware that is used to serve the static content could be mounted as follows:
  1. app.use(express.static(__dirname + '/public'));  
The express.static function takes the folder path to be publically served and returns the middleware to be mounted with the app.

Setting express view engine

The view engines could be set to handle the view compilation. The view engine could be set as given below.
  1. app.engine(‘jade’, require(‘jade’)._express);  
Here the jade engine will be used to compile the view when the view with .jade extension is found. Be sure that before setting the view engine, you have installed the jade engine using NPM.

Application routing

The express application can be done using the express.Router middleware or app.VERB functions, where VERBs are get, post, put, delete and all.

Multiple callbacks could be used with the single VERB. When the request comes in by matching the path given, the first callback will be executed, then the next() call executes the second callback function registered with the route.
  1. app.get(‘/’, function(req, res, next) {   
  2.     next() // invokes the next callback.  
  3. });  
  4. app.get(‘/’, function(req, res, next) {   
  5.     //The callback to be executed after the first one.  
  6. });  
In the get VERB, the first callback registered will be executed when a matching request is found, then the next() call invokes the second callback on the same route.
  1.  app.route('/api)  
  2. .all(requestAuth)  
  3. .get(function() { //... });  
  4. .put(function() { //... });  
  5. .delete(function() { //... });  
  6. .post(function() { //... });   
In the code above, we have shown all the ways to capture the requests on the "/api" route.

Conclusion

In this article part, we have discussed the basic parts of ExpressJS by which we can create a web application using NodeJS. In my next part, we shall discuss the KoaJS web framework for NodeJS.

Thanks for reading, Happy Coding.


Similar Articles