SoFunction
Updated on 2025-03-03

Express project file directory description and detailed explanation of function description

: Startup file, or entry file

: Stores project information and module dependencies. When adding dependencies to dependencies, run npm install. npm will check the current directory and automatically install all specified modules.

node_modules: Stores the installed modules in . After you add dependent modules and install them, store them in this folder.

public: store image, css, js and other files

routes: store routing files

views: store view files or template files

bin: store executable files

Open it 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
('views', (__dirname, 'views'));
('view engine', 'ejs');

// uncomment after placing your favicon in /public
//(favicon(__dirname + '/public/'));
(logger('dev'));
(());
(({ extended: false }));
(cookieParser());
(((__dirname, 'public')));

('/', routes);
('/users', users);

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

// error handlers

// development error handler
// will print stacktrace
if (('env') === 'development') {
    (function(err, req, res, next) {
        ( || 500);
        ('error', {
            message: ,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
(function(err, req, res, next) {
    ( || 500);
    ('error', {
        message: ,
        error: {}
    });
});


 = app;

Here we load modules such as express, path, etc. through require(), as well as index.js and routing files in the routes folder. Let’s explain the meaning of each line of code below.

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

(2)('views', (__dirname, 'views')): Set the views folder to the directory where the view files are stored, that is, where the template files are stored. __dirname is a global variable, and stores the directory where the script currently being executed is located.

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

(4)(favicon(__dirname + '/public/')): Set /public/ to the favicon icon.

(5)(logger('dev')): Load log middleware.

(6)(()): Load the middleware to parse json.

(7)(({ extended: false })): Load the middleware to parse the urlencoded request body.

(8)(cookieParser()): Load the middleware for parsing cookies.

(9)(((__dirname, 'public'))): Set the public folder to the directory where static files are stored.

(10)('/', routes); and ('/users', users): routing controller.

(11)

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

Catch 404 errors and forward to the error handler.

(12)

if (('env') === 'development') {
    (function(err, req, res, next) {
        ( || 500);
        ('error', {
            message: ,
            error: err
        });
    });
}

An error processor in the development environment renders the error template and displays it to the browser.

(13)

(function(err, req, res, next) {
    ( || 500);
    ('error', {
        message: ,
        error: {}
    });
});

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

(14) = app: Export the app instance for call from other modules.

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

#!/usr/bin/env node
var debug = require('debug')('blog');
var app = require('../app');

('port',  || 3000);

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

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

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

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

(4)('port', || 3000): Set the port number.

(5)

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

Start the project and listen to port 3000, and print Express server listening on port 3000 after success.

Let's look at routes/ file again:

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

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

 = router;

Generate a routing instance to capture the GET request to access the home page, export the route and load it in ('/', routes);. In this way, when accessing the home page, ('index', { title: 'Express' }); render the views/template and display it in the browser.

Let's look at the views/ file again:

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

When rendering the template, we pass in a variable title string with the value of express. 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 learn how to create a project and start it, understand the general structure and operation process of the project. In the next section, we will learn the basic use of express and routing control.

Summarize

This is the article about the directory description of the express project file and function description. For more related express project file directory content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!