express project file directory description and detailed function description

express project file directory description and detailed function description

app.js: startup file, or entry file

package.json: stores project information and module dependencies. When you add dependent modules to dependencies and run npm install, npm will check the package.json in the current directory and automatically install all specified modules.

node_modules: stores the modules installed in package.json. When you add dependent modules to package.json and install them, they are stored in this folder.

public: stores image, css, js and other files

routes: store routing files

views: store view files or template files

bin: stores executable files

Open app.js and let's see what's inside:

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');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

//view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(__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')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
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
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;

Here we use require() to load modules such as express and path, as well as the index.js and users.js routing files in the routes folder. Let's explain the meaning of each line of code.

(1) var app = express(): Generates an express instance app.

(2)app.set('views', path.join(__dirname, 'views')): Set the views folder to the directory where view files are stored, that is, where template files are stored. __dirname is a global variable that stores the directory where the currently executing script is located.

(3)app.set('view engine', 'ejs'): Set the view template engine to ejs.

(4)app.use(favicon(__dirname + '/public/favicon.ico')): Sets /public/favicon.ico as the favicon icon.

(5)app.use(logger('dev')): Load the logging middleware.

(6)app.use(bodyParser.json()): loads the middleware for parsing JSON.

(7)app.use(bodyParser.urlencoded({ extended: false })): Loads the middleware that parses the urlencoded request body.

(8)app.use(cookieParser()): Loads the middleware for parsing cookies.

(9)app.use(express.static(path.join(__dirname, 'public'))): Set the public folder to the directory where static files are stored.

(10) app.use('/', routes); and app.use('/users', users): route controllers.

(11)

app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

Capture 404 errors and forward them to the error handler.

(12)

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
        });
    });
}

The error handler in the development environment renders the error message to the error template and displays it in the browser.

(13)

app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

Error handlers in production environments will not leak error information to users.

(14)module.exports = app : Export the app instance for other modules to call.

Let's look at the bin/www file again:

#!/usr/bin/env node
var debug = require('debug')('blog');
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);
});

(1)#!/usr/bin/env node: indicates that it is the node executable file.

(2)var debug = require('debug')('blog'): Import the debug module and print the debug log.

(3)var app = require('../app'): Import the app instance we exported above.

(4)app.set('port', process.env.PORT || 3000): Set the port number.

(5)

var server = app.listen(app.get('port'), function() {
  debug('Express server listening on port ' + server.address().port);
});

Start the project and listen to port 3000. If successful, it will print Express server listening on port 3000.

Let's look at the routes/index.js file again:

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

Generate a routing instance to capture GET requests to access the home page, export this route and load it in app.js through app.use('/', routes); In this way, when you visit the homepage, res.render('index', { title: 'Express' }); will be called to render the views/index.ejs template and display it in the browser.

Let's take a look at the views/index.ejs file:

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
  </body>
</html>

When rendering the template, we passed in a variable title whose value is the express string. The template engine will replace all <%= title %> with express, and then display the rendered HTML to the browser, as shown in the figure above.

In this section, we learned how to create a project and start it, and understood the general structure and operation process of the project. In the next section, we will learn the basic use of express and route control.

Summarize

This is the end of this article about the express project file directory description and function description. For more relevant express project file directory content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of how nodejs express automatically generates project framework
  • Detailed explanation of express project layering practice

<<:  How to modify mysql permissions to allow hosts to access

>>:  Detailed example of changing Linux account password

Recommend

Analysis of the Linux input subsystem framework principle

Input subsystem framework The linux input subsyst...

Detailed explanation of MySQL index selection and optimization

Table of contents Index Model B+Tree Index select...

Solve the MySQL login 1045 problem under centos

Since the entire application needs to be deployed...

How to install and uninstall open-vswitch in Linux

1. Compile and install ovs from source code: Inst...

Example of how to build a Harbor public repository with Docker

The previous blog post talked about the Registry ...

Tutorial on upgrading, installing and configuring supervisor on centos6.5

Supervisor Introduction Supervisor is a client/se...

How to use less in WeChat applet (optimal method)

Preface I am used to writing less/sass, but now I...

The whole process record of vue3 recursive component encapsulation

Table of contents Preface 1. Recursive components...

Detailed explanation of nginx optimization in high concurrency scenarios

In daily operation and maintenance work, nginx se...

How to collect Nginx logs using Filebeat

Nginx logs can be used to analyze user address lo...

Samba server configuration under Centos7 (actual combat)

Samba Overview Samba is a free software that impl...

HTML form tag tutorial (1):

Forms are a major external form for implementing ...

Canvas draws scratch card effect

This article shares the specific code for drawing...

Introduction to MyCat, the database middleware

1. Mycat application scenarios Mycat has been dev...