Node.js 教程
Node.js 是什么、能做什么、这套教程怎么学。
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它擅长什么
| Scenario | Why Node fits |
|---|---|
| API 网关、BFF | I/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学习路线
- 装环境 —— nvm 管版本,npm 管依赖
- 懂异步 —— 回调、Promise、async/await、事件循环
- 会 I/O —— Buffer、Stream、fs
- 搭服务 —— http、Express、RESTful API
- 连数据 —— 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.Node.js 是什么
Node.js 是一个运行时,不是语言、不是框架。它把 Chrome 的 V8 引擎单独拎出来,再配上一套标准库(文件、网络、进程),于是 JavaScript 第一次能脱离浏览器跑在服务器上。
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它擅长什么
| 场景 | 为什么合适 |
|---|---|
| API 网关、BFF | I/O 密集,事件循环不阻塞 |
| 实时通信 | WebSocket 长连接开销小 |
| 前端工具链 | 和浏览器同一门语言,AST 生态成熟 |
| CPU 密集计算 | 不合适 —— 会卡住事件循环 |
一句话:I/O 密集选 Node,CPU 密集换语言或开子进程。图像处理、视频转码、复杂加密这类活交给 worker_threads 或独立服务。
一个最小的服务器
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学习路线
- 装环境 —— nvm 管版本,npm 管依赖
- 懂异步 —— 回调、Promise、async/await、事件循环
- 会 I/O —— Buffer、Stream、fs
- 搭服务 —— http、Express、RESTful API
- 连数据 —— MySQL、MongoDB
本教程所有示例都在 Node 22 LTS 上验证过。低于 18 的版本跑不了
node: 前缀的部分模块,也跑不了内置的 fetch。