Node.js 命令参考:本地开发服务器与生产环境服务器用法
一份可查阅的命令参考手册,涵盖 Node.js 版本管理、包管理器、环境配置、调试、PM2 以及无中断 Linux 部署相关内容。
来源: Node.js Cheatsheet — Essential Commands for Developers and Vibe Coders in 2026
nodejs
人工智能辅助编码彻底改变了项目开发的方式。你只需描述所需的结果,AI助手便会生成代码,几分钟内就能让程序运行起来。然而仍有一些情况是任何助手都无法帮上忙的——比如当你盯着终端窗口,需要知道该输入的确切命令时。
也许远程服务器上的部署出现了问题,也许安装过程在半途失败,又或许环境变量无法加载,或者某个进程崩溃后没有留下有用的堆栈跟踪信息。在这类情况下,你不想翻阅厚厚的文档——你需要的是能在几秒钟内快速查找到的信息。
这就是本参考手册的用途:它为两种场景提供了简明的Node.js命令指南——在本地机器上开发,以及管理生产服务器。每条命令都附有简短说明,告诉你何时该使用它。
运行 Node.js
首先从那些无需多想就应掌握的基础知识开始:
# Run a JavaScript file
node app.js
# Run with an environment variable inline
NODE_ENV=production node app.js
# Open the REPL (Read-Eval-Print Loop) - interactive Node.js shell
node
# Evaluate JavaScript directly from the terminal
node -e "console.log(process.version)"
# Check the active Node.js version
node -v
node --version
# Check the active npm version
npm -v
实用的 CLI 参数
# Watch mode — auto-restart when files change (Node.js 18+, no nodemon needed)
node --watch app.js
# Enable ES Modules
node --input-type=module app.js
# Increase memory limit for heavy applications
node --max-old-space-size=4096 app.js
# Show longer stack traces
node --stack-trace-limit=50 app.js
# Inspect mode for debugging with Chrome DevTools
node --inspect app.js
node --inspect-brk app.js # Pause at first line until debugger connects
Node.js 版本管理 — NVM
对于同时处理多个需要不同 Node.js 版本的项目的人来说,nvm(Node 版本管理器)已不再是锦上添花的功能,而是不可或缺的工具。
# Install a specific Node.js version
nvm install 22
nvm install 20.11.0 # Exact version
nvm install --lts # Latest LTS
# Switch versions
nvm use 22
nvm use --lts
# Set a default version
nvm alias default 22
# List all installed versions
nvm ls
# List available remote versions
nvm ls-remote --lts
# Use the version specified in .nvmrc
nvm use
# Create .nvmrc - lock the Node.js version for this project
echo "22" > .nvmrc
包管理器 — npm、yarn 和 pnpm
选择包管理器并非单纯出于风格偏好——每种选项都有其实际的利弊权衡。
进入 2026 年后,ppnm 已成为大多数团队的合理默认选择。它安装速度快、磁盘空间利用率高,能避免虚拟依赖问题,并提供最强大的单仓库工具支持。相关工具的支持也在不断跟进——Next.js、Nuxt 和 SvelteKit 等框架在 pnpm 上都能顺畅运行。
不过,哪种工具最合适取决于您的具体情况:
- npm — 默认随 Node.js 一起提供,可在任何环境中使用,是个人项目和开源包的可靠选择
- yarn — 在大型企业级单仓库项目中表现优异,尤其是与 Plug'n'Play(PnP)结合使用时
- pnpm — 速度最快且存储效率最高,是2026年生产环境及单仓库项目的首选
核心命令 — 三种包管理器的对比
# Install all dependencies from package.json
npm install
yarn install
pnpm install
# Add a new package
npm install express
yarn add express
pnpm add express
# Add as a devDependency
npm install -D typescript
yarn add -D typescript
pnpm add -D typescript
# Remove a package
npm uninstall express
yarn remove express
pnpm remove express
# Update packages
npm update
yarn upgrade
pnpm update
# Update to latest (beyond semver range in package.json)
npm install express@latest
yarn add express@latest
pnpm add express@latest
# Install without modifying the lockfile - required in CI/CD
npm ci
yarn install --frozen-lockfile
pnpm install --frozen-lockfile
# Run a script from package.json
npm run build
yarn build
pnpm build
# Run a package executable without installing globally
npx create-next-app
yarn dlx create-next-app
pnpm dlx create-next-app
package.json — 最常用的部分
{
"name": "my-app",
"version": "1.0.0",
"engines": {
"node": ">=20.0.0",
"npm": ">=10.0.0"
},
"scripts": {
"dev": "node --watch src/index.js",
"start": "node src/index.js",
"build": "tsc -p tsconfig.json",
"test": "node --test",
"lint": "eslint src/",
"format": "prettier --write src/"
},
"dependencies": {},
"devDependencies": {},
"type": "module"
}
审计与安全
# Check for vulnerabilities in dependencies
npm audit
yarn audit
pnpm audit
# Auto-fix vulnerabilities where possible
npm audit fix
yarn audit --fix
pnpm audit --fix
# List all installed packages (including nested)
npm list
npm list --depth=0 # Top-level only
# Check for outdated packages
npm outdated
yarn outdated
pnpm outdated
环境变量
环境变量能让您在开发环境和生产环境之间分开配置。避免在源代码文件中硬编码API密钥或数据库地址等敏感信息。
# Create a .env file
cat > .env << EOF
NODE_ENV=development
PORT=3000
DATABASE_URL=postgresql://localhost:5432/mydb
JWT_SECRET=your-secret-key
EOF
# Make sure .env never enters version control
echo ".env" >> .gitignore
echo ".env.local" >> .gitignore
echo ".env.production" >> .gitignore
# Create .env.example as a template for your team
cp .env .env.example
# Then remove the sensitive values from .env.example
在您的 Node.js 代码中:
// Node.js 20.6+ — load .env without any extra package
// Run with: node --env-file=.env app.js
// Or use dotenv for more flexibility
import 'dotenv/config';
const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;
const nodeEnv = process.env.NODE_ENV || 'development';
// Validate required env vars at startup - fail fast
const required = ['DATABASE_URL', 'JWT_SECRET'];
for (const key of required) {
if (!process.env[key]) {
console.error(`Missing required environment variable: ${key}`);
process.exit(1);
}
}
模块系统 — CommonJS 与 ES Modules
Node.js 仍然支持两种模块格式,但新项目应默认使用 ES Modules,因为它是与浏览器共享的现代标准。
// CommonJS (CJS) — the legacy format, .js or .cjs files
const fs = require('fs');
const path = require('path');
const express = require('express');
module.exports = { myFunction };
module.exports.default = MyClass;
// ES Modules (ESM) - the modern format, .mjs or .js with "type":"module"
import fs from 'fs';
import path from 'path';
import express from 'express';
import { readFile, writeFile } from 'fs/promises';
export function myFunction() {}
export default class MyClass {}
// Dynamic import - for lazy loading
const module = await import('./heavy-module.js');
文件系统 — 最常用的操作
import { readFile, writeFile, appendFile,
mkdir, rm, stat, readdir,
copyFile, rename } from 'fs/promises';
import { existsSync } from 'fs';
import path from 'path';
// Read a file
const content = await readFile('data.txt', 'utf-8');
const json = JSON.parse(await readFile('config.json', 'utf-8'));
// Write a file
await writeFile('output.txt', 'Hello World', 'utf-8');
await writeFile('data.json', JSON.stringify(data, null, 2));
// Append to an existing file
await appendFile('log.txt', `${new Date().toISOString()} - event\n`);
// Create a directory (including missing parents)
await mkdir('logs/2026/06', { recursive: true });
// Delete a file or directory
await rm('temp-file.txt');
await rm('dist/', { recursive: true, force: true });
// Check if a file or directory exists
if (existsSync('config.json')) {
// file exists
}
// Get file metadata
const info = await stat('app.js');
console.log(info.size); // size in bytes
console.log(info.isDirectory());
console.log(info.mtime); // last modified time
// Read directory contents
const files = await readdir('./src');
const jsFiles = files.filter(f => f.endsWith('.js'));
// Path helpers - always use path.join, never string concatenation
const filePath = path.join(__dirname, 'public', 'index.html');
const ext = path.extname('script.js'); // '.js'
const base = path.basename('/src/app.js'); // 'app.js'
const dir = path.dirname('/src/app.js'); // '/src'
HTTP 服务器 — 内置,无需框架
import { createServer } from 'http';
import { createReadStream } from 'fs';
const server = createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
const method = req.method;
// Simple routing
if (url.pathname === '/' && method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Hello World</h1>');
return;
}
if (url.pathname === '/api/health' && method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok', timestamp: new Date() }));
return;
}
// Read body from a POST request
if (method === 'POST') {
let body = '';
for await (const chunk of req) {
body += chunk;
}
const data = JSON.parse(body);
// process data...
}
// 404
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not Found' }));
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
进程管理
// Graceful shutdown — close connections before the process exits
process.on('SIGTERM', async () => {
console.log('SIGTERM received, shutting down...');
await db.disconnect();
server.close(() => {
console.log('Server closed');
process.exit(0);
});
});
process.on('SIGINT', async () => {
// Ctrl+C in terminal
await cleanup();
process.exit(0);
});
// Catch unhandled errors
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err);
process.exit(1); // Must exit - process state is now unreliable
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection:', reason);
process.exit(1);
});
// Process information
console.log(process.pid); // Process ID
console.log(process.env.NODE_ENV); // Environment
console.log(process.argv); // CLI arguments
console.log(process.cwd()); // Current working directory
console.log(process.memoryUsage()); // Memory usage
调试
# Inspect mode — open chrome://inspect in your browser
node --inspect app.js
# Pause at the first line until the debugger connects
node --inspect-brk app.js
# Enable verbose logging for specific modules
NODE_DEBUG=http,net node app.js
# CPU profiling
node --prof app.js
node --prof-process isolate-*.log > processed.txt
# Memory leak detection
node --expose-gc --inspect app.js
在您的代码中:
// util.debuglog — only outputs when the DEBUG env var is set
import { debuglog } from 'util';
const debug = debuglog('myapp');
debug('This only appears when: NODE_DEBUG=myapp node app.js');
// Simple timing
console.time('database-query');
await db.query('SELECT * FROM users');
console.timeEnd('database-query');
// Output: database-query: 23.456ms
PM2 — 生产环境进程管理工具
PM2 是在生产环境中运行 Node.js 的首选工具。它能在应用崩溃或服务器重启后自动重启,并且几乎无需额外配置即可实现跨 CPU 核心的扩展。
# Install PM2 globally
npm install -g pm2
# Start an application
pm2 start app.js
pm2 start app.js --name "my-api"
# Start in cluster mode - uses all available CPU cores
pm2 start app.js -i max # Automatically matches CPU core count
pm2 start app.js -i 4 # Exactly 4 instances
# View status of all applications
pm2 list
pm2 status
# Real-time monitoring (CPU, memory, logs)
pm2 monit
# View logs
pm2 logs
pm2 logs my-api
pm2 logs --lines 100
# Restart, reload, stop, delete
pm2 restart my-api
pm2 reload my-api # Zero-downtime reload (cluster mode only)
pm2 stop my-api
pm2 delete my-api
# Auto-restart on server reboot
pm2 startup # Generates the systemd command - follow the output
pm2 save # Saves the current process list
# Configuration file
// ecosystem.config.js
export default {
apps: [{
name: 'my-api',
script: 'src/index.js',
instances: 'max',
exec_mode: 'cluster',
watch: false,
max_memory_restart: '500M',
env: {
NODE_ENV: 'development',
PORT: 3000,
},
env_production: {
NODE_ENV: 'production',
PORT: 8080,
},
error_file: 'logs/err.log',
out_file: 'logs/out.log',
log_date_format: 'YYYY-MM-DD HH:mm:ss',
}]
};
# Start from the config file
pm2 start ecosystem.config.js
pm2 start ecosystem.config.js --env production
部署到 Linux 服务器
以下是在 VPS 或 Linux 服务器上首次安装 Node.js 时应遵循的步骤。
# 1. Update the system
sudo apt update && sudo apt upgrade -y
# 2. Install Node.js via NodeSource (latest LTS)
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt install -y nodejs
# Or install via nvm for easier version management
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install --lts
nvm use --lts
# 3. Verify the installation
node -v
npm -v
# 4. Install PM2 globally
npm install -g pm2
# 5. Clone and set up the project
git clone https://github.com/username/my-app.git
cd my-app
# 6. Install production dependencies only
npm ci --omit=dev
# or with pnpm
pnpm install --prod --frozen-lockfile
# 7. Create the production .env
nano .env
# 8. Start with PM2
pm2 start ecosystem.config.js --env production
pm2 save
pm2 startup # Follow the printed instructions
无停机更新部署
# Pull the latest code
git pull origin main
# Install any new dependencies
npm ci --omit=dev
# Build if needed
npm run build
# Zero-downtime reload (cluster mode only)
pm2 reload my-api
# Or a standard restart
pm2 restart my-api
Node.js 维护过程中实际会用到的 Linux 命令
# Check what's running on a specific port
lsof -i :3000
sudo netstat -tlnp | grep :3000
sudo ss -tlnp | grep :3000
# Kill whatever is on a port
kill $(lsof -t -i:3000)
# Or forcefully
kill -9 $(lsof -t -i:3000)
# Real-time resource monitoring
htop # Interactive (install with: apt install htop)
top # Built-in alternative
# Disk usage
df -h # Per partition
du -sh node_modules/ # Size of a specific directory
du -sh * # Size of everything in the current directory
# Follow logs in real time
journalctl -u pm2-root -f # PM2 logs via systemd
tail -f /var/log/syslog # System log
tail -f logs/err.log # Your application error log
# Memory overview
free -h
# Active network connections
ss -s
# Find all running Node.js processes
ps aux | grep node
# Find files by name or age
find . -name "*.log" -mtime +7 # .log files older than 7 days
find . -name "*.env" # Any .env files
# Clean up old logs
find ./logs -name "*.log" -mtime +30 -delete
# Archive a folder for backup
tar -czf backup-$(date +%Y%m%d).tar.gz dist/ .env
# Transfer files to/from a server
scp -r ./dist user@server:/var/www/my-app/
rsync -avz ./dist/ user@server:/var/www/my-app/dist/
.npmrc 与 .nvmrc —— 两个至关重要的小文件
虽然这两个配置文件看起来很简单,但一旦开始团队协作就会显得非常重要。
# .nvmrc — pin the Node.js version for this project
# Place at the project root
echo "22" > .nvmrc
# Everyone on the team just runs:
nvm use
# NVM automatically reads the version from .nvmrc
# .npmrc — npm/pnpm configuration for this project
# Place at the project root
# Save exact versions (no ^ or ~ prefix)
save-exact=true
# Set registry (if using a private registry)
registry=https://registry.npmjs.org/
# For pnpm - allow hoisting if a package requires it
# shamefully-hoist=true
# For pnpm - set the node linker
# node-linker=hoisted
测试 —— Node.js 内置测试运行器
从 Node.js 20 版本开始,运行时本身就包含了测试运行器。对于简单的测试套件,完全可以不必安装 Jest 或 Mocha。
// test/app.test.js
import { test, describe, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert/strict';
describe('Calculator', () => {
test('addition works correctly', () => {
assert.equal(1 + 1, 2);
});
test('throws on division by zero', () => {
assert.throws(
() => divide(10, 0),
{ message: 'Cannot divide by zero' }
);
});
test('async operation resolves correctly', async () => {
const result = await fetchUser(1);
assert.equal(result.id, 1);
assert.ok(result.name);
});
});
# Run all tests
node --test
# Run a specific test file
node --test test/app.test.js
# Watch mode - re-run on file changes
node --test --watch
# With coverage (Node.js 22+)
node --test --experimental-test-coverage
预生产环境检查清单
在将 Node.js 应用上线之前,请先查看这份清单:
- 已设置
NODE_ENV=production——这将启用 Express 及其他库的性能优化功能 - 应用所需的每个环境变量都存在于服务器上,而不仅是在本地的
.env文件中 - 您使用的是
npm ci --omit=dev而非npm install,因此只有生产环境所需的依赖会被安装 - 锁定文件(
package-lock.json或pnpm-lock.yaml)已被提交到 git——跳过此步骤可能导致 CI/CD 使用与测试时不同的依赖版本 - 已实现优雅关闭机制,能够正确处理 SIGTERM 和 SIGINT 信号
- 已配置错误监控功能——
unhandledRejection和uncaughtException事件会被记录并触发警报
总结
无需一次性记住本手册中的所有内容。将其加入书签,每当忘记某个命令时再查看,久而久之,工作流程就会自然而然地牢记在心。
在我们当前这种快速编码的阶段,AI 工具确实很擅长生成代码和搭建完整项目框架——但当你在深夜遇到故障的生产服务器时,真正有帮助的其实是熟练掌握各种工具,而不是反复试错或惊慌失措。
首先重点关注那些你会频繁使用的部分:包管理器、环境变量以及 PM2。其他内容会在你需要时自然而然地明确起来。