Node.js 简介

Node.js 让 JavaScript 可以在浏览器之外运行,基于 Chrome V8 引擎。它的事件驱动、非阻塞 I/O 模型非常适合高并发 I/O 密集型应用,比如 API 服务、实时通信。

npm 包管理

# 初始化项目(生成 package.json)
npm init -y

# 安装依赖
npm install express        # 生产依赖
npm install -D nodemon     # 开发依赖
npm uninstall express      # 卸载

# 运行脚本(package.json 的 scripts)
npm run dev

package.json 里的 scripts 是项目命令入口,常用:

{
  "scripts": {
    "dev": "node server.js",
    "start": "node server.js"
  }
}

第一个 HTTP 服务

// 原生 http 模块
const http = require("http");

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
  res.end("你好,Node.js!");
});

server.listen(3000, () => {
  console.log("服务已启动:http://localhost:3000");
});

用 Express 框架更简洁:

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

app.get("/", (req, res) => res.send("首页"));
app.get("/api/users", (req, res) => res.json([{ id: 1, name: "小明" }]));

app.listen(3000, () => console.log("服务已启动"));
第 1 / 3 节