跳至正文

💚 什么是Node.js?

📖 定义

Node.js是构建在Chrome V8引擎上的JavaScript运行时。它使JavaScript能够在浏览器外执行,通过异步事件驱动架构提供高性能和可扩展性。通过npm(Node Package Manager)提供庞大的库生态系统。

🎯 简单类比

餐厅厨房

传统服务器(同步)
└─ 一个厨师按顺序服务客户(慢)

Node.js(异步)
├─ 一个厨师同时处理多个订单
├─ 煮牛排时 → 准备沙拉
└─ 快速高效!

⚙️ 事件循环

┌─────────────┐
│ Call Stack │ 执行代码
└──────┬──────┘

┌──────▼──────┐
│ Event Loop │ 协调器
└──────┬──────┘

┌────┴─────┐
│ │
Microtask Task Queue
(Promise) (setTimeout)

💡 关键示例

基本HTTP服务器

const http = require('http');

const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>你好,Node.js!</h1>');
});

server.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});

Express API

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

app.use(express.json());

app.get('/api/users', (req, res) => {
res.json([
{ id: 1, name: '张三' },
{ id: 2, name: '李四' }
]);
});

app.post('/api/users', (req, res) => {
const newUser = req.body;
res.status(201).json({ message: '创建成功', user: newUser });
});

app.listen(3000);

Async/Await

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

// ❌ 顺序执行(慢)
async function readSequential() {
const file1 = await fs.readFile('file1.txt');
const file2 = await fs.readFile('file2.txt');
// 总计:200ms
}

// ✅ 并行执行(快)
async function readParallel() {
const [file1, file2] = await Promise.all([
fs.readFile('file1.txt'),
fs.readFile('file2.txt')
]);
// 总计:100ms(并发)
}

数据库集成

const express = require('express');
const mysql = require('mysql2/promise');

const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydb'
});

app.get('/api/users', async (req, res) => {
try {
const [rows] = await pool.execute('SELECT * FROM users');
res.json(rows);
} catch (error) {
res.status(500).json({ error: '数据库错误' });
}
});

🤔 常见问题

Q1. 为什么Node.js快?

// 非阻塞I/O
readFile('file.txt', (err, data) => {
processData(data);
});
// 读取时可以处理其他请求!

// 事件驱动
// 单线程处理数千个连接
// 无上下文切换开销

Q2. 什么是npm?

# Node.js的包管理器
npm install express # 安装包
npm init -y # 初始化项目
npm list # 列出已安装的包
npm audit # 安全检查

# package.json
{
"dependencies": {
"express": "^4.18.0"
}
}

Q3. CommonJS vs ES模块?

// CommonJS(传统)
const { add } = require('./math');
module.exports = { add };

// ES模块(现代)
import { add } from './math.js';
export function add(a, b) { return a + b; }

// 在package.json中启用
{ "type": "module" }

🎬 总结

  • 异步I/O: 高性能和可扩展性
  • JavaScript: 与前端相同的语言
  • npm: 庞大的包生态系统
  • 事件循环: 高效的并发处理

使用Node.js成为全栈开发者! 💚