[Express version 4.x] Creating Express application with command prompt

express
この記事は約5分で読めます。

To make application development easier, we can choose using Express template framework for Node.js application development.

Here is the quick note how to install Express and what inside in app.js.

Express installation

You may follow these steps to install Express in your computer.

Express installation

Install Express by typing following commands.

$ npm install express

Or you may install express with global option (-g).

$ npm install -g express

Quick Start Express

The easiest way to create express applications is that generating applications by express command. And then you may customize that generated application after.

Generating applications

$ npm install -g express
$ express /tmp/foo && cd /tmp/foo

Install dependencies

$ npm install -d

Starting the server

$ node app.js

What is “app.js”?

After generating your Express applications by express command, you will find “app.js” that is the basic file for all applications.

//Load required modules
var createError = require('http-errors');

//Creates an Express application. 
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

//Load JS files in "routes/index" folder
var indexRouter = require('./routes/index'); 

//Load JS files in "routes/users" folder
var usersRouter = require('./routes/users'); 

//The express() function is a top-level function exported by the express module.
var app = express();

// view engine setup
// view is like template files for displaying
// "__dirname" = directory path to the application
app.set('views', path.join(__dirname, 'views'));

// "view engine" specifies template engine to jade or ejs.
app.set('view engine', 'jade');

//"app.use" mounts the specified middleware function or functions at the specified path. 
// Middleware is like a plugin to expand Express function.
app.use(logger('dev')); // logger: function for exporting log files.
app.use(express.json()); 
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser()); // cookieParser: function for using cookie function

//static: All files in 'public' can be set as static files.
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

//"module" creates modules that can be used as shared modules.
module.exports = app;

Reference

About how to generate express applications, refer to expressjs.com.

タイトルとURLをコピーしました