Node.js

Node.js 开发指南 #

Node.js 是基于 Chrome V8 引擎的 JavaScript 运行时,适合构建快速、可扩展的服务器端应用。

快速开始 #

基础 HTTP 服务器 #

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, World!');
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

Express.js 框架 #

const express = require('express');
const app = express();

// 中间件
app.use(express.json());
app.use(express.static('public'));

// 路由
app.get('/api/users', async (req, res) => {
  try {
    const users = await getUsersFromDB();
    res.json(users);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

核心模块 #

文件系统操作 #

const fs = require('fs').promises;
const path = require('path');

async function readConfig() {
  try {
    const configPath = path.join(__dirname, 'config.json');
    const data = await fs.readFile(configPath, 'utf8');
    return JSON.parse(data);
  } catch (error) {
    console.error('Config file not found:', error);
    return {};
  }
}

异步处理 #

```javascript function fetchData(url) { return fetch(url) .then(response => response.json()) .then(data => processData(data)) .catch(error => console.error('Error:', error)); } ```
```javascript async function fetchData(url) { try { const response = await fetch(url); const data = await response.json(); return processData(data); } catch (error) { console.error('Error:', error); throw error; } } ```

常用包推荐 #

Web 框架 #

  • Express - 最流行的 Node.js 框架
  • Fastify - 高性能替代方案
  • Koa - Express 团队的现代框架

数据库 #

  • Mongoose - MongoDB ODM
  • Prisma - 现代数据库工具包
  • Sequelize - SQL ORM

工具库 #

  • Lodash - 实用工具库
  • Moment.js/Day.js - 日期处理
  • Winston - 日志记录
**安全注意事项** - 使用 helmet 设置安全头 - 验证和清理用户输入 - 使用环境变量存储敏感信息 - 定期更新依赖包