阿里云主机折上折
  • 微信号
Current Site:Index > Express Generator scaffolding tool

Express Generator scaffolding tool

Author:Chuan Chen 阅读数:8012人阅读 分类: Node.js

Introduction to the Express Generator Scaffolding Tool

Express Generator is an official command-line tool provided by the Express team for quickly generating the basic structure of an Express application. Through predefined templates and configurations, it helps developers skip repetitive initialization work and dive straight into business logic development.

Installing Express Generator

Installing Express Generator globally is very simple—just run the following npm command:

npm install -g express-generator

After installation, you can verify whether the installation was successful by running the express --version command. For developers who only want to use it in the current project, it can also be installed locally:

npm install express-generator --save-dev

Basic Usage

The basic command format for creating a new Express project is:

express [options] [dir]

Here, the dir parameter specifies the project directory name. If not specified, the project will be created in the current directory. Common options include:

  • -v, --view <engine>: Specifies the template engine (default is Jade).
  • -c, --css <engine>: Specifies the CSS preprocessor (e.g., Less, Stylus, or Sass).
  • --git: Adds a .gitignore file.
  • -f, --force: Forces project creation in a non-empty directory.

For example, to create a project using the EJS template engine and SASS:

express --view=ejs --css=sass myapp

Analysis of the Generated Project Structure

The standard project structure generated by Express Generator includes the following key components:

myapp/
├── app.js
├── bin/
│   └── www
├── package.json
├── public/
│   ├── images/
│   ├── javascripts/
│   └── stylesheets/
├── routes/
│   ├── index.js
│   └── users.js
└── views/
    ├── error.jade
    ├── index.jade
    └── layout.jade

app.js is the core entry file of the application, containing middleware configurations and route settings. bin/www is the startup script, handling server listening and port settings. The public directory stores static resources, routes contains routing logic, and views holds template files.

Customizing Project Configuration

Although Express Generator provides reasonable default configurations, developers often need to adjust them based on project requirements. For example, to modify the default port in bin/www:

var port = normalizePort(process.env.PORT || '3000');

To add new middleware, insert it in the appropriate location in app.js:

// Add body-parser middleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

Template Engine Support

Express Generator supports various popular template engines, specified via the --view option:

express --view=pug myapp  # Use Pug (Jade)
express --view=ejs myapp  # Use EJS
express --view=hbs myapp  # Use Handlebars

For example, with EJS, the generated view file would look like this:

<!-- views/index.ejs -->
<!DOCTYPE html>
<html>
<head>
    <title><%= title %></title>
</head>
<body>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
</body>
</html>

Routing System Breakdown

The generated project includes basic routing configurations. routes/index.js handles requests to the root path:

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

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

To add a new route, create a new routing file and register it in app.js:

// routes/about.js
var express = require('express');
var router = express.Router();

router.get('/', function(req, res) {
  res.send('About Page');
});

module.exports = router;

// Add in app.js
var aboutRouter = require('./routes/about');
app.use('/about', aboutRouter);

Static Resource Handling

Express Generator automatically configures static file middleware:

app.use(express.static(path.join(__dirname, 'public')));

This means files in the public directory can be accessed directly via URLs. For example, public/stylesheets/style.css can be accessed at /stylesheets/style.css.

For static resources requiring CDN or special handling, additional static directories can be added:

app.use('/cdn', express.static(path.join(__dirname, 'cdn-assets')));

Error Handling Mechanism

The generated project includes basic error-handling middleware:

// Catch 404 errors
app.use(function(req, res, next) {
  next(createError(404));
});

// Error handler
app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  
  res.status(err.status || 500);
  res.render('error');
});

Developers can extend this error-handling logic, such as adding logging:

app.use(function(err, req, res, next) {
  console.error(err.stack);
  next(err);
});

Database Integration

While Express Generator doesn't directly include database configurations, it can easily be integrated. For MongoDB, first install Mongoose:

npm install mongoose

Then add the connection code in app.js:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myapp', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

Create a model file, models/user.js:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
  name: String,
  email: String
});

module.exports = mongoose.model('User', userSchema);

Testing Support

Express Generator doesn't include testing configurations, but they can be easily added. For Jest:

npm install --save-dev jest supertest

Create tests/app.test.js:

const request = require('supertest');
const app = require('../app');

describe('GET /', () => {
  it('responds with 200', async () => {
    await request(app)
      .get('/')
      .expect(200);
  });
});

Add a test script to package.json:

"scripts": {
  "test": "jest"
}

Production Environment Deployment

For production deployment, the bin/www generated by Express Generator already covers basic needs. However, additional steps are required:

  1. Set environment variables:
export NODE_ENV=production
  1. Use a process manager like PM2:
npm install -g pm2
pm2 start ./bin/www
  1. Configure a reverse proxy (Nginx example):
server {
    listen 80;
    server_name example.com;
    
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Extending Generator Functionality

Developers can create their own Express Generator templates. First, fork the official repository, then modify the file structure in the /templates directory. Key files include:

  • js/ - Contains various template files.
  • support/ - Helper code.
  • cli.js - Command-line interface.

After modifications, test locally using npm link:

npm link
express --my-custom-option

Common Issue Resolution

Issue 1: Port already in use. Solution: Modify the port number in bin/www or kill the occupying process:

lsof -i :3000
kill -9 <PID>

Issue 2: Template engine not rendering. Check if the view engine is correctly configured in app.js:

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

Issue 3: Static resources returning 404. Ensure the public directory exists and middleware is loaded correctly:

app.use(express.static(path.join(__dirname, 'public')));

Integration with Other Tools

Express Generator can integrate with modern frontend toolchains. For example, with Webpack:

  1. Install dependencies:
npm install --save-dev webpack webpack-cli babel-loader @babel/core
  1. Create webpack.config.js:
module.exports = {
  entry: './public/javascripts/main.js',
  output: {
    path: __dirname + '/public/dist',
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  }
};
  1. Reference the bundled file in templates:
<script src="/dist/bundle.js"></script>

Performance Optimization Recommendations

  1. Enable compression middleware:
npm install compression
const compression = require('compression');
app.use(compression());
  1. Set cache headers:
app.use(express.static(path.join(__dirname, 'public'), {
  maxAge: '1d'
}));
  1. Use cluster mode:
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
} else {
  // Server startup code
}

Security Best Practices

  1. Set security-related HTTP headers:
npm install helmet
const helmet = require('helmet');
app.use(helmet());
  1. Prevent CSRF attacks:
npm install csurf
const csrf = require('csurf');
const csrfProtection = csrf({ cookie: true });
app.use(csrfProtection);
  1. Limit request body size:
app.use(express.json({ limit: '10kb' }));
app.use(express.urlencoded({ extended: true, limit: '10kb' }));

Modernization Directions

For projects already created with Express Generator, consider the following modernization improvements:

  1. Convert to ES modules:
// package.json
"type": "module"
  1. Refactor routes using async/await:
router.get('/', async (req, res, next) => {
  try {
    const data = await fetchData();
    res.render('index', { data });
  } catch (err) {
    next(err);
  }
});
  1. Add TypeScript support:
npm install --save-dev typescript @types/express @types/node

Create tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "outDir": "./dist",
    "rootDir": "./",
    "strict": true,
    "esModuleInterop": true
  }
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.