- Node.js Blueprints
- Krasimir Tsonev
- 1381字
- 2021-07-16 11:36:14
Installing Express
There are two ways to install Express. We'll will start with the simple one and then proceed to the more advanced technique. The simpler approach generates a template, which we may use to start writing the business logic directly. In some cases, this can save us time. From another viewpoint, if we are developing a custom application, we need to use custom settings. We can also use the boilerplate, which we get with the advanced technique; however, it may not work for us.
Using package.json
Express is like every other module. It has its own place in the packages register. If we want to use it, we need to add the framework in the package.json
file. The ecosystem of Node.js is built on top of the Node Package Manager. It uses the JSON file to find out what we need and installs it in the current directory. So, the content of our package.json
file looks like the following code:
{ "name": "projectname", "description": "description", "version": "0.0.1", "dependencies": { "express": "3.x" } }
These are the required fields that we have to add. To be more accurate, we have to say that the mandatory fields are name
and version
. However, it is always good to add descriptions to our modules, particularly if we want to publish our work in the registry, where such information is extremely important. Otherwise, the other developers will not know what our library is doing. Of course, there are a bunch of other fields, such as contributors, keywords, or development dependencies, but we will stick to limited options so that we can focus on Express.
Once we have our package.json
file placed in the project's folder, we have to call npm install
in the console. By doing so, the package manager will create a node_modules
folder and will store Express and its dependencies there. At the end of the command's execution, we will see something like the following screenshot:

The first line shows us the installed version, and the proceeding lines are actually modules that Express depends on. Now, we are ready to use Express. If we type require('express')
, Node.js will start looking for that library inside the local node_modules
directory. Since we are not using absolute paths, this is normal behavior. If we miss running the npm install
command, we will be prompted with Error: Cannot find module 'express'
.
Using a command-line tool
There is a command-line instrument called express-generator
. Once we run npm install -g express-generator
, we will install and use it as every other command in our terminal.
If you use the framework in several projects, you will notice that some things are repeated. We can even copy and paste them from one application to another, and this is perfectly fine. We may even end up with our own boilerplate and can always start from there. The command-line version of Express does the same thing. It accepts few arguments and based on them, creates a skeleton for use. This can be very handy in some cases and will definitely save some time. Let's have a look at the available arguments:
-h, --help
: This signifies output usage information.-V, --version
: This shows the version of Express.-e, --ejs
: This argument adds the EJS template engine support. Normally, we need a library to deal with our templates. Writing pure HTML is not very practical. The default engine is set to JADE.-H, --hogan
: This argument is Hogan-enabled (another template engine).-c, --css
: If we want to use the CSS preprocessors, this option lets us use LESS (short for Leaner CSS) or Stylus. The default is plain CSS.-f, --force
: This forces Express to operate on a nonempty directory.
Let's try to generate an Express application skeleton with LESS as a CSS preprocessor. We use the following line of command:
express --css less myapp
A new myapp
folder is created with the file structure, as seen in the following screenshot:

We still need to install the dependencies, so cd myapp && npm install
is required. We will skip the explanation of the generated directories for now and will move to the created app.js
file. It starts with initializing the module dependencies, as follows:
var express = require('express'); var path = require('path'); var favicon = require('static-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes/index'); var users = require('./routes/users'); var app = express();
Our framework is express
, and path
is a native Node.js module. The middleware are favicon
, logger
, cookieParser
, and bodyParser
. The routes
and users
are custom-made modules, placed in local for the project folders. Similarly, as in the Model-View-Controller (MVC) pattern, these are the controllers for our application. Immediately after, an app
variable is created; this represents the Express library. We use this variable to configure our application. The script continues by setting some key-value pairs. The next code snippet defines the path to our views and the default template engine:
app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade');
The framework uses the methods set
and get
to define the internal properties. In fact, we may use these methods to define our own variables. If the value is a Boolean, we can replace set
and get
with enable
and disable
. For example, see the following code:
app.set('color', 'red'); app.get('color'); // red app.enable('isAvailable');
The next code adds middleware to the framework. We can see the code as follows:
app.use(favicon()); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(cookieParser()); app.use(require('less-middleware')({ src: path.join(__dirname, 'public') })); app.use(express.static(path.join(__dirname, 'public')));
The first middleware serves as the favicon of our application. The second is responsible for the output in the console. If we remove it, we will not get information about the incoming requests to our server. The following is a simple output produced by logger
:
GET / 200 554ms - 170b GET /stylesheets/style.css 200 18ms - 110b
The json
and urlencoded
middleware are related to the data sent along with the request. We need them because they convert the information in an easy-to-use format. There is also a middleware for the cookies. It populates the request object, so we later have access to the required data. The generated app uses LESS as a CSS preprocessor, and we need to configure it by setting the directory containing the .less
files. We will talk about LESS in Chapter 10, Writing Flexible and Modular CSS, where will cover this in detail. Eventually, we define our static resources, which should be delivered by the server. These are just few lines, but we've configured the whole application. We may remove or replace some of the modules, and the others will continue working. The next code in the file maps two defined routes to two different handlers, as follows:
app.use('/', routes); app.use('/users', users);
If the user tries to open a missing page, Express still processes the request by forwarding it to the error handler, as follows:
app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); });
The framework suggests two types of error handling: one for the development environment and another for the production server. The difference is that the second one hides the stack trace of the error, which should be visible only for the developers of the application. As we can see in the following code, we are checking the value of the env
property and handling the error differently:
// development error handler if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); });
At the end, the app.js
file exports the created Express instance, as follows:
module.exports = app;
To run the application, we need to execute node ./bin/www
. The code requires app.js
and starts the server, which by default listens on port 3000
.
#!/usr/bin/env node var debug = require('debug')('my-application'); var app = require('../app'); app.set('port', process.env.PORT || 3000); var server = app.listen(app.get('port'), function() { debug('Express server listening on port ' + server.address().port); });
The process.env
declaration provides an access to variables defined in the current development environment. If there is no PORT
setting, Express uses 3000 as the value. The required debug
module uses a similar approach to find out whether it has to show messages to the console.
- Go Web編程
- MySQL數據庫管理實戰
- 小程序實戰視頻課:微信小程序開發全案精講
- 大學計算機應用基礎實踐教程
- Maven Build Customization
- C++面向對象程序設計(微課版)
- Magento 2 Development Cookbook
- Python數據分析(第2版)
- 從學徒到高手:汽車電路識圖、故障檢測與維修技能全圖解
- OpenShift在企業中的實踐:PaaS DevOps微服務(第2版)
- PhoneGap Mobile Application Development Cookbook
- ASP.NET Core 2 Fundamentals
- 響應式Web設計:HTML5和CSS3實戰(第2版)
- Java圖像處理:基于OpenCV與JVM
- Orleans:構建高性能分布式Actor服務