P(rocess)M(anager)2 是一個 node.js 下的進程管理器,內置負載均衡,支持應用自動重啟,常用于生產環境運行 node.js 應用,非常好用👍
🌼概述
2025-03-15日,PM2發布最新版本v6.0.5
,這是一個大版本升級(上一版本v5.4.2
發布于24年7月),本次更新帶來了 Bun.js 的支持🎉。
- 支持
Bun.js
運行時 - 默認禁用
git
解析 - PM2 serve 響應增加
WEBP
內容類型
??版本升級
此處以 windows 平臺為例進行說明
# 查看當前版本
pm2 -v
# 5.3.0# 直接通過以下命令覆蓋安裝
npm i -g pm2
# added 13 packages, removed 63 packages, and changed 121 packages in 1m
# 13 packages are looking for funding
# run `npm fund` for details
升級后,我們執行 pm2 ls
(顯示pm2管理的進程)命令,會得到以下提示:
>>>> In-memory PM2 is out-of-date, do:
>>>> $ pm2 update
In memory PM2 version: 5.3.0
Local PM2 version: 6.0.5
我們執行pm2 update
即可。
$ pm2 update-------------██████╗ ███╗ ███╗██████╗ ██╗ ██╗ ██████╗██╔══██╗████╗ ████║╚════██╗ ██║ ██╔╝██╔═══██╗██████╔╝██╔████╔██║ █████╔╝ ██║ ██╔╝ ██║ ██║██╔═══╝ ██║╚██╔╝██║██╔═══╝ ██║ ██╔╝ ██║ ██║██║ ██║ ╚═╝ ██║███████╗ ██║██╔╝ ╚██████╔╝╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═╝╚═╝ ╚═════╝https://pm2.io/Harden your Node.js Production Environment- Real-time Monitoring Web Interface- Pro Active Alerting System- Production Profiling for Memory and CPU- PM2 Runtime High Availability FallbackStart using it by typing:$ pm2 plus-------------[PM2][WARN] No process found
[PM2] [v] All Applications Stopped
[PM2] [v] PM2 Daemon Stopped
[PM2] Spawning PM2 daemon with pm2_home=C:\Users\admin\.pm2
[PM2] Restoring processes located in C:\Users\admin\.pm2\dump.pm2
>>>>>>>>>> PM2 updated
🛠?小試牛刀
安裝 Bun.js
如果您已經安裝,請跳過😄
# windows 下安裝 bun.js
powershell -c "irm bun.sh/install.ps1|iex"# 升級
bun upgrade# 卸載
powershell -c ~\.bun\uninstall.ps1
示例代碼
我們讓 deepseek 寫一段簡單的 WEB 服務
import http from 'http';
import url from 'url';// 記錄程序啟動時間
const startTime = Date.now();// 創建 HTTP 服務器
const server = http.createServer((req, res) => {const parsedUrl = url.parse(req.url, true);// 處理 /status 路由if (parsedUrl.pathname === '/status') {// 計算程序已經運行的時間(秒)const uptime = Math.floor((Date.now() - startTime) / 1000);// 返回 JSON 響應res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ uptime }));} else {// 處理其他路由res.writeHead(404, { 'Content-Type': 'text/plain' });res.end('Not Found');}
});// 監聽端口
const PORT = 3000;
server.listen(PORT, () => {console.log(`Server is running on http://localhost:${PORT}`);
});
運行進程
# 使用 node.js 運行
pm2 start web-node.mjs --interpreter node
# 使用 bun.js 運行
pm2 start web-bun.mjs --interpreter bun
運行4h后的狀態:
運行7h后的狀態:
Bun.js 跑的應用占用的內存越來越低?😂