Node.js

Node.js是一个基于Chrome V8引擎的JavaScript运行时环境,允许开发者使用JavaScript编写服务器端代码。

核心概念

1. 事件驱动

Node.js采用事件驱动、非阻塞I/O模型,使其轻量高效。

javascript
const fs = require('fs');

// 非阻塞读取文件
fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

console.log('File reading started...');

2. 模块系统

Node.js使用CommonJS模块系统,通过require()module.exports进行模块管理。

javascript
// math.js (模块定义)
module.exports = {
  add: (a, b) => a + b,
  subtract: (a, b) => a - b
};

// app.js (模块使用)
const math = require('./math');
console.log(math.add(5, 3)); // 输出: 8

3. npm

npm是Node.js的包管理器,用于安装、共享和管理依赖。

bash
# 安装包
npm install express

# 全局安装
npm install -g nodemon

# 创建package.json
npm init

环境安装

1. 安装Node.js

访问Node.js官网下载并安装适合你操作系统的版本。

2. 验证安装

bash
# 检查Node.js版本
node -v

# 检查npm版本
npm -v

基础应用

创建简单的HTTP服务器

javascript
const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, Node.js!\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

使用Express框架

Express是Node.js最流行的Web框架。

javascript
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello, Express!');
});

app.get('/users', (req, res) => {
  res.json([{ name: 'Alice' }, { name: 'Bob' }]);
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

核心模块

Node.js提供了丰富的核心模块:

  • http/https: 创建HTTP/HTTPS服务器和客户端
  • fs: 文件系统操作
  • path: 路径处理
  • os: 操作系统信息
  • events: 事件处理
  • util: 工具函数
  • crypto: 加密功能
  • stream: 流处理

异步编程

Node.js大量使用异步编程,主要方式有:

1. 回调函数

javascript
fs.readFile('file.txt', (err, data) => {
  if (err) throw err;
  console.log(data);
});

2. Promise

javascript
const { promisify } = require('util');
const readFileAsync = promisify(fs.readFile);

readFileAsync('file.txt')
  .then(data => console.log(data))
  .catch(err => console.error(err));

3. Async/Await

javascript
async function readFile() {
  try {
    const data = await readFileAsync('file.txt');
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

readFile();

最佳实践

  1. 使用异步I/O:避免阻塞事件循环
  2. 错误处理:始终处理异步操作的错误
  3. 模块化设计:将代码拆分为小的、可复用的模块
  4. 使用npm:合理管理项目依赖
  5. 性能监控:使用工具监控应用性能

学习资源

最后更新:2026-02-08