Node.js 教程

Node.js 是什么、能做什么、这套教程怎么学。

Beginner
Key PointsNode.js 把 V8 引擎搬出浏览器,让 JavaScript 能读写文件、开端口、连数据库。

Node.js 是什么

Node.js is a runtime, not a language and not a framework. It lifts Chrome's V8 engine out and pairs it with a standard library (files, network, processes), so JavaScript can finally run on a server outside the browser.

JavaScript
// hello.js
const os = require('node:os');

console.log('平台:', os.platform());
console.log('CPU 核数:', os.cpus().length);
console.log('Node 版本:', process.version);
Output
平台: win32
CPU 核数: 8
Node 版本: v22.22.2

它擅长什么

ScenarioWhy Node fits
API 网关、BFFI/O 密集,事件循环不阻塞
实时通信WebSocket 长连接开销小
前端工具链和浏览器同一门语言,AST 生态成熟
CPU 密集计算不合适 —— 会卡住事件循环

In one line: Node for I/O-bound work, another language or child processes for CPU-bound work. Image processing, transcoding and heavy crypto belong in worker_threads or a separate service.

一个最小的服务器

JavaScript
const http = require('node:http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
  res.end('Hello, Node.js\n');
});

server.listen(3000, () => {
  console.log('http://127.0.0.1:3000');
});
Output
$ node server.js
http://127.0.0.1:3000

$ curl http://127.0.0.1:3000
Hello, Node.js

学习路线

  1. 装环境 —— nvm 管版本,npm 管依赖
  2. 懂异步 —— 回调、Promise、async/await、事件循环
  3. 会 I/O —— Buffer、Stream、fs
  4. 搭服务 —— http、Express、RESTful API
  5. 连数据 —— MySQL、MongoDB
Every example here is verified on Node 22 LTS. Anything below 18 cannot use some node:-prefixed modules or the built-in fetch.

Friends & Partners