阿里云主机折上折
  • 微信号
Current Site:Index > Introduction to commonly used plugins and extension libraries

Introduction to commonly used plugins and extension libraries

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

Introduction to Common Plugins and Extension Libraries

Express, as one of the most popular web frameworks for Node.js, excels due to its rich middleware ecosystem. Through plugins and extension libraries, developers can quickly implement features like route management, template rendering, and database connections, significantly improving development efficiency.

Middleware Plugins

body-parser

Middleware for handling HTTP request body data, supporting JSON, URL-encoded, and multipart formats:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json()); // Parse JSON format
app.use(bodyParser.urlencoded({ extended: true })); // Parse URL-encoded format

app.post('/api/users', (req, res) => {
  console.log(req.body); // Access POST request body data
  res.sendStatus(200);
});

morgan

HTTP request logger with support for multiple log formats:

const morgan = require('morgan');
app.use(morgan('combined')); // Use standard Apache combined log format
// Other formats include dev, tiny, short, etc.

helmet

Security middleware that automatically sets HTTP security headers:

const helmet = require('helmet');
app.use(helmet()); // Enable all security middleware by default
// Can be configured individually: app.use(helmet.contentSecurityPolicy());

Template Engine Extensions

ejs

Embedded JavaScript templating engine:

app.set('view engine', 'ejs');
app.get('/', (req, res) => {
  res.render('index', { title: 'EJS Example', items: ['a', 'b', 'c'] });
});

Corresponding template file:

<!-- views/index.ejs -->
<h1><%= title %></h1>
<ul>
  <% items.forEach(item => { %>
    <li><%= item %></li>
  <% }); %>
</ul>

pug

High-performance templating engine (formerly Jade):

app.set('view engine', 'pug');
app.get('/profile', (req, res) => {
  res.render('profile', { user: { name: 'John', age: 28 } });
});

Template example:

//- views/profile.pug
doctype html
html
  body
    h1= user.name
    p Age: #{user.age}

Database Integration

mongoose

MongoDB object modeling tool:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

const UserSchema = new mongoose.Schema({
  name: String,
  email: { type: String, unique: true }
});
const User = mongoose.model('User', UserSchema);

app.post('/users', async (req, res) => {
  const user = new User(req.body);
  await user.save();
  res.json(user);
});

sequelize

ORM supporting various SQL databases:

const { Sequelize, Model, DataTypes } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:');

class User extends Model {}
User.init({
  username: DataTypes.STRING,
  birthday: DataTypes.DATE
}, { sequelize });

app.get('/users', async (req, res) => {
  const users = await User.findAll();
  res.json(users);
});

Utility Libraries

lodash

JavaScript utility library:

const _ = require('lodash');

app.get('/api/products', (req, res) => {
  const rawProducts = getProductsFromDB(); // Assume returns an array
  const filtered = _.filter(rawProducts, p => p.price > 100);
  const sorted = _.sortBy(filtered, 'name');
  res.json(_.take(sorted, 10));
});

moment

Date handling library (note: now in maintenance mode):

const moment = require('moment');

app.get('/events', (req, res) => {
  const now = moment();
  const events = getEvents().filter(e => 
    moment(e.date).isBetween(now, now.clone().add(1, 'month'))
  );
  res.json(events);
});

Testing Related

supertest

HTTP assertion library:

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

describe('GET /users', () => {
  it('responds with JSON', done => {
    request(app)
      .get('/users')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200, done);
  });
});

jest

Testing framework integration:

const { createServer } = require('../server');

let server;
beforeAll(() => { server = createServer(); });
afterAll(() => { server.close(); });

test('GET /ping returns pong', async () => {
  const res = await request(server).get('/ping');
  expect(res.statusCode).toBe(200);
  expect(res.text).toBe('pong');
});

Performance Optimization

compression

Response compression middleware:

const compression = require('compression');
app.use(compression()); // Uses zlib compression by default
// Configurable: app.use(compression({ level: 6 }));

express-rate-limit

API rate-limiting middleware:

const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100 // Limit each IP to 100 requests
});
app.use('/api/', limiter);

Real-Time Communication

socket.io

WebSocket real-time communication library:

const http = require('http');
const socketio = require('socket.io');

const server = http.createServer(app);
const io = socketio(server);

io.on('connection', socket => {
  console.log('New client connected');
  socket.on('chat message', msg => {
    io.emit('chat message', msg);
  });
});

server.listen(3000);

File Handling

multer

File upload middleware:

const multer = require('multer');
const upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('avatar'), (req, res) => {
  console.log(req.file); // Uploaded file information
  res.send('Upload successful');
});

sharp

High-performance image processing library:

const sharp = require('sharp');

app.get('/thumbnail', async (req, res) => {
  const buffer = await sharp('input.jpg')
    .resize(200, 200)
    .toBuffer();
  res.type('image/jpeg').send(buffer);
});

Authentication & Authorization

passport

Authentication middleware:

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
  (username, password, done) => {
    User.findOne({ username }, (err, user) => {
      if (err) return done(err);
      if (!user) return done(null, false);
      if (!user.verifyPassword(password)) return done(null, false);
      return done(null, user);
    });
  }
));

app.post('/login', 
  passport.authenticate('local', { 
    successRedirect: '/',
    failureRedirect: '/login'
  })
);

jsonwebtoken

JWT implementation:

const jwt = require('jsonwebtoken');

app.post('/api/auth', (req, res) => {
  const token = jwt.sign(
    { userId: 123 }, 
    'your-secret-key', 
    { expiresIn: '1h' }
  );
  res.json({ token });
});

Development Tools

nodemon

Hot-reload tool for development:

// package.json
{
  "scripts": {
    "dev": "nodemon server.js"
  }
}

dotenv

Environment variable management:

require('dotenv').config();

app.get('/config', (req, res) => {
  res.json({
    dbHost: process.env.DB_HOST,
    apiKey: process.env.API_KEY
  });
});

Deployment Related

pm2

Process manager for production environments:

pm2 start server.js -i max --name "my-api"
pm2 save
pm2 startup

cors

Cross-Origin Resource Sharing middleware:

const cors = require('cors');
app.use(cors()); // Allow all cross-origin requests
// Configurable: app.use(cors({ origin: 'https://example.com' }));

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

如果侵犯了你的权益请来信告知我们删除。邮箱: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 ☕.