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

How to use axios request in Vue project

Table of contents 1. Installation 2. There is no ...

js to realize the mouse following game

This article shares the specific code of js to im...

Example code for setting hot links and coordinate values ​​for web images

Sometimes you need to set several areas on a pict...

Vue Element front-end application development to obtain back-end data

Table of contents Overview 1. Acquisition and pro...

How to use CSS to display multiple images horizontally in the center

Let me first talk about the implementation steps:...

Detailed installation and use of virtuoso database under Linux system

I've been researching some things about linke...

A brief discussion on how Tomcat breaks the parent delegation mechanism

Table of contents JVM Class Loader Tomcat class l...

js implements mouse in and out card switching content

This article shares the specific code of js to re...

Detailed explanation of common commands in MySQL 8.0+

Enable remote access Enable remote access rights ...

A friendly alternative to find in Linux (fd command)

The fd command provides a simple and straightforw...

Docker nginx example method to deploy multiple projects

Prerequisites 1. Docker has been installed on the...

Steps to purchase a cloud server and install the Pagoda Panel on Alibaba Cloud

Alibaba Cloud purchases servers Purchase a cloud ...

JavaScript Basics Objects

Table of contents 1. Object 1.1 What is an object...