返回首页

Node.js 全面入门教程

Node.js 全面入门教程

1. Node.js 简介

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时环境。它让 JavaScript 可以脱离浏览器在服务器端运行。

主要特点

  • 事件驱动:非阻塞 I/O 模型,使其轻量且高效。
  • 单线程:使用单线程处理并发连接,避免了多线程上下文切换的开销。
  • 跨平台:可以在 Windows、Linux、macOS 等系统上运行。

适用场景

  • 实时应用 (聊天室、协作工具)
  • API 服务器 (RESTful, GraphQL)
  • 流媒体应用
  • 命令行工具 (CLI)

2. 环境安装

访问 Node.js 官网 下载对应系统的安装包。建议下载 LTS (长期支持版),因为更加稳定。

安装完成后,在终端检查版本:

node -v
npm -v

3. 第一个 Node.js 程序

创建一个名为 app.js 的文件,输入以下代码:

// app.js
const message = "Hello, Node.js!";
console.log(message);

运行:

node app.js

4. 模块系统 (Module System)

Node.js 遵循 CommonJS 规范,但现代版本也完全支持 ES Modules。

4.1 CommonJS (默认)

导出模块 (math.js):

const add = (a, b) => a + b;
const subtract = (a, b) => a - b;

module.exports = { add, subtract };

导入模块 (index.js):

const math = require("./math");
console.log(math.add(5, 3)); // 输出: 8

4.2 ES Modules (推荐)

package.json 中添加 "type": "module",或者使用 .mjs 后缀。

// math.js
export const add = (a, b) => a + b;

// index.js
import { add } from "./math.js";
console.log(add(2, 3));

5. 核心模块详解

Node.js 内置了许多强大的模块,无需安装即可使用。

5.1 fs (文件系统)

用于读写文件。建议使用 promises API 以配合 async/await。

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

async function fileOps() {
  try {
    // 写入文件
    await fs.writeFile("test.txt", "Hello Node File System");
    console.log("文件写入成功");

    // 读取文件
    const data = await fs.readFile("test.txt", "utf8");
    console.log("文件内容:", data);
  } catch (err) {
    console.error("操作失败:", err);
  }
}

fileOps();

5.2 path (路径处理)

处理文件路径,解决不同操作系统路径分隔符不一致的问题。

const path = require("path");

const filePath = path.join(__dirname, "files", "test.txt");
console.log(filePath);
// Windows: C:\project\files\test.txt
// Linux/Mac: /project/files/test.txt

console.log(path.extname(filePath)); // .txt

5.3 http (创建服务器)

创建一个基础的 Web 服务器。

const http = require("http");

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain; charset=utf-8");

  if (req.url === "/") {
    res.end("欢迎访问首页");
  } else if (req.url === "/about") {
    res.end("关于我们");
  } else {
    res.statusCode = 404;
    res.end("页面未找到");
  }
});

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

5.4 events (事件触发器)

Node.js 核心架构基于事件。

const EventEmitter = require("events");
const myEmitter = new EventEmitter();

// 注册监听器
myEmitter.on("userLoggedIn", (user) => {
  console.log(`用户 ${user} 已登录,发送欢迎邮件...`);
});

// 触发事件
myEmitter.emit("userLoggedIn", "Alice");

6. 异步编程 (Asynchronous Programming)

Node.js 最大的特点是非阻塞异步。

6.1 Promise 与 Async/Await

避免“回调地狱 (Callback Hell)”,让异步代码看起来像同步代码。

function simulateRequest() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("数据加载完成");
    }, 1000);
  });
}

async function main() {
  console.log("开始请求...");
  const result = await simulateRequest();
  console.log(result);
  console.log("请求结束");
}

main();

7. 包管理器 NPM

NPM (Node Package Manager) 是世界上最大的软件注册表。

  • 初始化项目: npm init -y (生成 package.json)
  • 安装依赖: npm install express
  • 安装开发依赖: npm install nodemon -D
  • 全局安装: npm install -g typescript

package.json 示例:

{
  "name": "my-node-app",
  "version": "1.0.0",
  "dependencies": {
    "express": "^4.18.2"
  },
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js"
  }
}

8. 实战:使用 Express 构建 REST API

Express 是 Node.js 最流行的 Web 框架,简化了路由和中间件的处理。

首先安装:npm install express

// server.js
const express = require("express");
const app = express();

// 中间件:解析 JSON 请求体
app.use(express.json());

// 模拟数据库
let users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
];

// GET: 获取所有用户
app.get("/api/users", (req, res) => {
  res.json(users);
});

// POST: 创建新用户
app.post("/api/users", (req, res) => {
  const newUser = {
    id: users.length + 1,
    name: req.body.name,
  };
  users.push(newUser);
  res.status(201).json(newUser);
});

// 启动服务器
app.listen(3000, () => {
  console.log("Express 服务器运行在 http://localhost:3000");
});

测试该 API 可以使用 Postman 或 curl。


9. 进阶学习路线

  1. 数据库: 学习连接 MongoDB (Mongoose) 或 SQL (Sequelize, Prisma, TypeORM)。
  2. 认证: 使用 JWT (JSON Web Tokens) 进行用户身份验证。
  3. TypeScript: 为 Node.js 项目增加类型安全。
  4. 测试: 学习使用 Jest 或 Mocha 编写单元测试。
  5. 部署: 学习如何将 Node.js 应用部署到服务器 (使用 PM2 进行进程管理, Docker 容器化)。