Node.js 从入门到上线实战指南(零基础 → 高手)

7 阅读4分钟

覆盖:Node 基础、ES6 模块化、npm、Express、MongoDB、项目实战、部署上线、HTTPS 证书配置


一、什么是 Node.js?

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境,让 JS 能运行在服务器端。

核心特点

  • 单线程 + 事件循环(Event Loop)
  • 非阻塞 I/O(高并发)
  • npm 生态强大

二、环境准备

1. 安装 Node.js

官网下载安装(LTS版本)

node -v
npm -v

三、Node.js 基础(零基础)

1. 第一个程序

console.log("Hello Node.js");

运行:

node app.js

2. 内置模块

const fs = require("fs");

fs.readFile("test.txt", "utf-8", (err, data) => {
  console.log(data);
});

常用模块:

  • fs(文件)
  • path(路径)
  • http(服务)

3. 创建 HTTP 服务(原生)

const http = require("http");

http.createServer((req, res) => {
  res.end("hello world");
}).listen(3000);

四、ES6 模块化(现代写法)

1. 开启模块化

{
  "type": "module"
}

2. 使用 import/export

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

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

五、npm(包管理)

1. 初始化项目

npm init -y

2. 安装依赖

npm install express
npm install -D nodemon

3. scripts 脚本

"scripts": {
  "dev": "nodemon app.js",
  "start": "node app.js"
}

六、Express 框架(重点)

1. 快速启动服务

import express from "express";

const app = express();

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

app.listen(3000);

2. 路由系统

app.get("/user", (req, res) => {
  res.json({ name: "Tom" });
});

3. 静态资源

app.use(express.static("public"));

4. 中间件

app.use(express.json());

app.use((req, res, next) => {
  console.log("请求来了");
  next();
});

七、MongoDB 数据库

1. 启动 MongoDB(Docker 推荐)

docker run -d -p 27017:27017 mongo

2. 使用 mongoose

npm install mongoose

3. 连接数据库

import mongoose from "mongoose";

mongoose.connect("mongodb://localhost:27017/test");

4. 定义模型

const UserSchema = new mongoose.Schema({
  name: String,
  age: Number
});

const User = mongoose.model("User", UserSchema);

5. CRUD

// 新增
await User.create({ name: "Tom", age: 20 });

// 查询
const users = await User.find();

八、项目实战(REST API)

1. 项目结构

project/
├── app.js
├── routes/
├── models/
├── public/

2. 示例 API

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

九、项目部署上线


1. Linux 服务器准备

sudo apt update
sudo apt install nodejs npm

2. 使用 PM2(进程管理)

npm install -g pm2
pm2 start app.js
pm2 save
pm2 startup

3. 使用 Nginx 反向代理

server {
  listen 80;

  location / {
    proxy_pass http://localhost:3000;
  }
}

十、HTTPS 证书配置(重点)

使用 Let's Encrypt 免费证书


1. 安装 certbot

sudo apt install certbot python3-certbot-nginx

2. 申请证书

sudo certbot --nginx

3. 自动续期

certbot renew --dry-run

十一、生产优化

1. 环境变量

NODE_ENV=production

2. 日志管理

使用 winston / morgan


3. 安全

npm install helmet

4. 跨域

import cors from "cors";
app.use(cors());

十二、总结

从零到上线你学会了:

  • Node.js 基础
  • ES6 模块化
  • npm 管理
  • Express 框架
  • MongoDB 数据库
  • REST API
  • PM2 部署
  • Nginx 反向代理
  • HTTPS 证书

🚀 进阶方向

  • 微服务架构
  • Docker 容器化
  • K8s 部署
  • GraphQL
  • WebSocket 实时通信

🚀 进阶方向(从工程到架构)

当你掌握了 Node.js + Express + MongoDB 的基础后,下一步要从“能写接口”进阶到“能做系统架构”。


一、微服务架构(Microservices)

📌 什么是微服务?

把一个大型系统拆分成多个小服务,每个服务独立运行:

用户服务  →  登录 / 注册
订单服务  →  下单 / 支付
商品服务  →  商品管理

🧱 Node.js 实现方式

最简单通信方式(HTTP):

// user-service
app.get("/user", (req, res) => {
  res.json({ id: 1, name: "Tom" });
});

// order-service 调用 user-service
import axios from "axios";

const user = await axios.get("http://localhost:3001/user");

🚀 常用技术

  • API Gateway(网关)
  • 服务注册发现(Consul / Nacos)
  • 消息队列(RabbitMQ / Kafka)

🎯 优点

  • 可独立部署
  • 高扩展性
  • 团队协作友好

二、Docker 容器化

📌 为什么要用 Docker?

解决“我本地能跑,你那跑不了”的问题


🐳 Dockerfile 示例

FROM node:18

WORKDIR /app

COPY . .

RUN npm install

EXPOSE 3000

CMD ["node", "app.js"]

▶️ 构建运行

docker build -t my-node-app .
docker run -p 3000:3000 my-node-app

📦 docker-compose(推荐)

version: "3"
services:
  app:
    build: .
    ports:
      - "3000:3000"
  mongo:
    image: mongo

🎯 优点

  • 环境一致
  • 快速部署
  • 易扩展

三、Kubernetes(K8s)部署

📌 是什么?

容器编排平台,用来管理大量 Docker 容器


🧱 Deployment 示例

apiVersion: apps/v1
kind: Deployment
metadata:
  name: node-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: node
  template:
    metadata:
      labels:
        app: node
    spec:
      containers:
        - name: node-app
          image: my-node-app
          ports:
            - containerPort: 3000

🌐 Service 暴露服务

apiVersion: v1
kind: Service
metadata:
  name: node-service
spec:
  type: NodePort
  selector:
    app: node
  ports:
    - port: 3000
      targetPort: 3000

🎯 能力

  • 自动扩容(HPA)
  • 服务发现
  • 灰度发布

四、GraphQL(替代 REST)

📌 为什么用 GraphQL?

客户端可以“按需获取数据”


🚀 Node 示例

npm install graphql express-graphql
import { graphqlHTTP } from "express-graphql";
import { buildSchema } from "graphql";

const schema = buildSchema(`
  type Query {
    hello: String
  }
`);

const root = {
  hello: () => "Hello GraphQL"
};

app.use("/graphql", graphqlHTTP({
  schema,
  rootValue: root,
  graphiql: true
}));

🎯 优点

  • 减少接口数量
  • 前端更灵活
  • 强类型

五、WebSocket 实时通信

📌 应用场景

  • 聊天系统
  • 实时通知
  • 在线游戏

🚀 Node 实现(ws)

npm install ws
import { WebSocketServer } from "ws";

const wss = new WebSocketServer({ port: 8080 });

wss.on("connection", (ws) => {
  ws.send("连接成功");

  ws.on("message", (msg) => {
    console.log("收到:", msg.toString());
  });
});

🎯 特点

  • 双向通信
  • 实时性强
  • 比 HTTP 更高效

🧠 进阶学习路线总结

Node基础
   ↓
Express + MongoDB
   ↓
REST API
   ↓
Docker(容器化)
   ↓
微服务架构
   ↓
K8s(集群部署)
   ↓
GraphQL / WebSocket(高级能力)

🎯 最终目标

👉 从“写接口”升级为:

  • ✔ 架构设计能力
  • ✔ 分布式系统思维
  • ✔ 可扩展系统构建能力

🚀 一句话总结

真正的 Node.js 高手,不只是会写接口,而是能设计系统。