Node.js = 浏览器 JS 引擎搬到服务端(V8 + 事件驱动 + 非阻塞 IO)。系列 15 篇从入门写到 PM2 部署,本篇先跑起来。
一、Node.js 是什么
组成:V8 引擎(Google,JS 执行) + libuv(异步 IO 事件循环)
特点:单线程事件驱动、非阻塞 IO、适合高并发 IO 密集型
场景:Web API、实时应用(WebSocket)、爬虫、CLI 工具、BFF 层
二、安装(nvm 管版本)
# 推荐:nvm 管理多版本
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
nvm install 20 # LTS 版
nvm use 20
node -v # v20.x.x
npm -v
# 或直接官网下载安装包(简单)
三、REPL 交互式编程
node # 进入 REPL(读取-求值-输出-循环)
> 1 + 1
2
> .help # 命令帮助
> .exit # 退出
REPL = 试代码的沙盒(类比 Python 的交互模式)。
四、第一个程序
// hello.js
const name = 'Node';
console.log(`你好,${name}!`);
node hello.js # 你好,Node!
五、第一个 HTTP 服务器
// server.js —— 5 行跑起 Web 服务
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
res.end('<h1>你好 Node!</h1>');
}).listen(3000, () => console.log('http://localhost:3000'));
node server.js & # 后台跑
curl http://localhost:3000
六、npm 与 npx
npm init -y # 初始化 package.json
npm install express # 装依赖
npm run dev # 跑脚本
npx create-react-app myapp # 临时执行(不用全局装)
七、注意
- 选 LTS 版(偶数版本如 18/20)用于生产;
- Windows 下 nvm 用 nvm-windows;
- node -v 与 npm -v 都要有(npm 随 node 装);
- Node 不是多线程:CPU 密集任务用 worker_threads 或队列(进阶篇讲)。
八、小案例:动态问候 HTTP 服务
// greet_server.js
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const query = url.parse(req.url, true).query;
const name = query.name || '访客';
const hour = new Date().getHours();
const greet = hour < 12 ? '早上好' : hour < 18 ? '下午好' : '晚上好';
res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
res.end(`<h1>${greet},${name}!</h1><p>服务器时间:${new Date().toLocaleString()}</p>`);
});
server.listen(3000, () => {
console.log('服务已启动: http://localhost:3000?name=Tom');
});
GET 参数解析 + 时间判断 + 动态 HTML —— 一个有交互感的入门服务(curl 或浏览器访问)。
九、总结
Node = V8 + 事件驱动;nvm 管版本;REPL 试代码;node xxx.js 跑脚本;http 模块 5 行起服务;npm init/install/run 三板斧。