Express.js is a Node.js web framework that has gained immense popularity due to its simplicity. It has easy-to-use routing and simple support for view engines, putting it far ahead of the basic Node HTTP server
However, starting a new Express application requires a certain amount of boilerplate code: starting a new server instance, configuring a view engine, setting up error handling.
Although there are various starter projects and boilerplates available, Express has its own command-line tool that makes it easy to start new apps, called the express-generator.
Express has a lot of features built in, and a lot more features you can get from other packages that integrate seamlessly, but there are three main things it does for you out of the box:
Starting a new project with the Express generator is as simple as running a few commands:
npm install express-generator -g
This installs the Express generator as a global package, allowing you to run the express
command in your terminal:
express myapp
This creates a new Express project called myapp
which is then placed inside of the myapp
directory.
cd myapp
If you’re unfamiliar with terminal commands, this one puts you inside of the myapp
directory.
npm install
npm is the default Node.js package manager. Running npm install
installs all dependencies for the project. By default, the express-generator
includes several packages that are commonly used with an Express server.
The generator CLI takes half a dozen arguments, but the two most useful ones are the following:
jade
. Although this still works, it has been deprecated in favor of pug
.Now that we’ve got our project set up and dependencies installed, we can start the new server by running the following:
npm start
Then browse to http://localhost:3000
in your browser.
The generated Express application starts off with four folders.
The bin
folder contains the executable file that starts your app. It starts the server (on port 3000, if no alternative is supplied) and sets up some basic error handling. You don’t really need to worry about this file because npm start
will run it for you.
The public
folder is one of the important ones: _everything_ in this folder is accessible to people connecting to your application. In this folder, you’ll put JavaScript, CSS, images, and other assets that people need when they connect to your website.
The routes
folder is where you’ll put your router files. The generator creates two files, index.js
and users.js
, which serve as examples of how to separate out your application’s route configuration.
Usually, here you’ll have a different file for each major route on your website. So you might have files called blog.js
, home.js
, and/or about.js
in this folder.
The views
folder is where you have the files used by your templating engine. The generator will configure Express to look in here for a matching view when you call the render
method.
Outside of these folders, there’s one file that you should know well.
The app.js
file is special because it sets up your Express application and glues all of the different parts together. Let’s walk through what it does. Here’s how the file starts:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
These first six lines of the file are requires. If you’re new to Node, be sure to read Understanding module.exports and exports in Node.js.
var routes = require('./routes/index');
var users = require('./routes/users');
The next two lines of code are requiring the different route files that the Express generator sets up by default: routes and users.
var app = express();
After that, we create a new app by calling express()
. The app variable contains all of the settings and routes for your application. This object glues together your application.
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
Once the app instance is created, the templating engine is set up for rendering views. This is where you’d change the path to your view files if you wanted.
After this, you’ll see Express being configured to use middleware. The generator installs several common pieces of middleware that you’re likely to use in a web application.
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
favicon.ico
out of your public directory.request.body
. The second line parses query string data in the URL (e.g. /profile?id=5
) and puts this in request.query
.request.cookies
. It also allows you to modify them before sending them back to the client, by changing response.cookies
.public
folder. If you wanted to rename or move the public folder, you can change the path here.Next up is the routing:
app.use('/', routes);
app.use('/users', users);
Here the example route files that were required are attached to our app. If you need to add additional routes, you’d do it here.
All the code after this is used for error handling. You usually won’t have to modify this code unless you want to change the way Express handles errors. By default, it’s set up to show the error that occurred in the route when you’re in development mode.
Hopefully you now have a clear idea of how the express-generator tool can save you time writing repetitive boilerplate when starting new Express-based projects.
By providing a sensible default file structure, and installing and wiring up commonly needed middleware, the generator creates a solid foundation for new applications with just a couple of commands.
☞ Crafting multi-stage builds with Docker in Node.js
☞ Introduction to Unit and Integration Testing for Node.js Applications
☞ Node.js vs PHP: Which is better for Backend Developer?
☞ JavaScript Programming Tutorial Full Course for Beginners
☞ Learn JavaScript - Become a Zero to Hero
☞ E-Commerce JavaScript Tutorial - Shopping Cart from Scratch