Node.js 快速上手教程
Node.js 快速上手建议按"安装 → 跑脚本 → 跑 TypeScript → 建 HTTP 服务 → 用内置 SQLite"这条主线,15 分钟就能跑通,且全程尽量用 2026 年的新特性。
1. 安装 Node.js
推荐用 nvm(多版本管理最干净):
# macOS / Linux
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash
source ~/.bashrc # 或 source ~/.zshrc
nvm install --ltsWindows 直接安装: 去 nodejs.org 下载 LTS 安装包,一路 Next,安装时不要勾选 "Tools for Native Modules"(会装几个 G 的 VS Build Tools)。
验证:
node -v # 建议 ≥ 24.x
npm -v国内加速:
npm config set registry https://registry.npmmirror.com2. 跑第一个脚本
创建 hello.js:
console.log("Hello, Node.js!");运行:
node hello.js3. 原生跑 TypeScript(2026 新特性)
Node.js 24.12+ 起 Type Stripping 已稳定,直接 node xxx.ts 即可运行。
创建 hello.ts:
interface User {
id: number;
name: string;
}
const users: User[] = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
];
for (const user of users) {
console.log(`${user.id}: ${user.name}`);
}直接运行:
node hello.ts注意: Node 只做"擦类型"不做类型检查,项目里仍建议保留 tsc --noEmit 做静态校验。 不支持 enum、参数属性等会生成运行时代码的语法。
开发时带热重载:
node --watch hello.ts4. 写一个 HTTP 服务
创建 server.js:
import { createServer } from "node:http";
const server = createServer((req, res) => {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Hello from Node.js!", time: new Date().toISOString() }));
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});运行并访问 http://localhost:3000:
node server.js5. 用内置 SQLite(2026 新特性)
Node.js 24.15+ 起 node:sqlite 已进入 Release Candidate,可直接使用。
创建 db.js:
import { DatabaseSync } from "node:sqlite";
const db = new DatabaseSync("./app.db");
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
email TEXT UNIQUE
)
`);
const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
insert.run("Alice", "alice@example.com");
insert.run("Bob", "bob@example.com");
const users = db.prepare("SELECT * FROM users").all();
console.log(users);
db.close();运行:
node db.js无需 npm install 任何包,数据库就是一个 .db 文件,拷走就能迁移。
6. 环境变量内置验证(2026 新特性)
创建 .env:
PORT=3000
DATABASE_URL=sqlite://./app.db
DEBUG=false创建 config.js:
import { env } from "node:process";
const config = env.validate({
PORT: { type: "number", default: 3000 },
DATABASE_URL: { type: "string", required: true },
DEBUG: { type: "boolean", default: false },
});
console.log(config);运行:
node --env-file=.env config.js不再需要 dotenv 包。
7. 权限模型(2026 新特性)
用最小权限运行服务:
node --permission --allow-fs-read=./app.db --allow-net=localhost:3000 server.js未授权的文件/网络访问会自动被拒绝。
8. 下一步
- 框架:Fastify(高性能 API)、NestJS(企业级)、Hono(跨运行时)
- ORM:Drizzle ORM(轻量、无需 codegen)、Prisma
- 测试:内置
node:test,无需 Jest - 包管理:
corepack enable后用pnpm