Appearance
Node.js 工具与资源
本章介绍Node.js开发中常用的工具、资源和最佳实践指南。
开发工具
包管理工具
npm (Node Package Manager)
bash
# 基础命令
npm init # 初始化项目
npm install <package> # 安装包
npm install --save <package> # 安装生产依赖
npm install --save-dev <package> # 安装开发依赖
npm uninstall <package> # 卸载包
npm list # 列出已安装的包
npm outdated # 检查过时的包
npm update # 更新包
npm audit # 检查安全漏洞
npm audit fix # 自动修复安全漏洞
# 高级命令
npm ci # 清理安装(用于CI/CD)
npm run <script> # 运行脚本
npm link # 创建符号链接
npm publish # 发布包
npm version <update_type> # 更新版本号
yarn
bash
# Yarn基础命令
yarn init # 初始化项目
yarn add <package> # 安装包
yarn add <package> --dev # 安装开发依赖
yarn remove <package> # 卸载包
yarn install # 安装依赖
yarn upgrade # 升级包
yarn run <script> # 运行脚本
yarn global add <package> # 全局安装
pnpm
bash
# pnpm基础命令
pnpm init # 初始化项目
pnpm add <package> # 安装包
pnpm add <package> -D # 安装开发依赖
pnpm remove <package> # 卸载包
pnpm install # 安装依赖
pnpm update # 更新包
pnpm run <script> # 运行脚本
版本管理工具
nvm (Node Version Manager)
bash
# 安装和使用nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# 常用命令
nvm install node # 安装最新版本
nvm install --lts # 安装最新LTS版本
nvm install 18.17.0 # 安装指定版本
nvm use 18.17.0 # 使用指定版本
nvm use --lts # 使用最新LTS版本
nvm list # 列出已安装版本
nvm alias default 18.17.0 # 设置默认版本
n (Node.js版本管理器)
bash
# 安装n
npm install -g n
# 使用n
n latest # 安装最新版本
n lts # 安装最新LTS版本
n 18.17.0 # 安装指定版本
n # 交互式选择版本
代码质量工具
ESLint (代码检查)
bash
# 安装ESLint
npm install --save-dev eslint
# 初始化ESLint配置
npx eslint --init
javascript
// .eslintrc.js
module.exports = {
env: {
browser: true,
es2021: true,
node: true
},
extends: [
'eslint:recommended',
'@typescript-eslint/recommended' // 如果使用TypeScript
],
parserOptions: {
ecmaVersion: 12,
sourceType: 'module'
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'warn',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'warn',
'prefer-const': 'error',
'no-var': 'error',
'semi': ['error', 'always'],
'quotes': ['error', 'single']
}
};
Prettier (代码格式化)
bash
# 安装Prettier
npm install --save-dev prettier
json
// .prettierrc
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"bracketSpacing": true,
"arrowParens": "avoid"
}
代码质量集成
json
// package.json
{
"scripts": {
"lint": "eslint src/**/*.js",
"lint:fix": "eslint src/**/*.js --fix",
"format": "prettier --write src/**/*.js",
"format:check": "prettier --check src/**/*.js",
"precommit": "lint-staged"
},
"lint-staged": {
"*.js": [
"eslint --fix",
"prettier --write",
"git add"
]
},
"devDependencies": {
"eslint": "^8.0.0",
"prettier": "^2.0.0",
"lint-staged": "^13.0.0"
}
}
测试工具
Jest (测试框架)
bash
# 安装Jest
npm install --save-dev jest
javascript
// jest.config.js
module.exports = {
testEnvironment: 'node',
collectCoverage: true,
coverageDirectory: 'coverage',
collectCoverageFrom: [
'src/**/*.js',
'!src/**/*.test.js',
'!src/**/*.spec.js'
],
testMatch: [
'**/__tests__/**/*.(js|jsx|ts|tsx)',
'**/*.(test|spec).(js|jsx|ts|tsx)'
],
setupFilesAfterEnv: ['<rootDir>/test/setup.js']
};
Supertest (API测试)
bash
npm install --save-dev supertest
javascript
// test/api.test.js
const request = require('supertest');
const app = require('../app');
describe('API测试', () => {
test('GET /api/users 应该返回用户列表', async () => {
const response = await request(app)
.get('/api/users')
.expect(200);
expect(Array.isArray(response.body)).toBe(true);
});
});
构建和打包工具
Webpack
bash
npm install --save-dev webpack webpack-cli webpack-node-externals
javascript
// webpack.config.js
const path = require('path');
const nodeExternals = require('webpack-node-externals');
module.exports = {
mode: 'production',
entry: './src/index.js',
target: 'node',
externals: [nodeExternals()],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/
}
]
}
};
Parcel
bash
npm install --save-dev parcel
json
// package.json
{
"scripts": {
"build": "parcel build src/index.js --target node",
"dev": "parcel watch src/index.js --target node"
}
}
监控和性能工具
PM2 (进程管理器)
bash
# 全局安装PM2
npm install -g pm2
javascript
// ecosystem.config.js
module.exports = {
apps: [{
name: 'my-app',
script: './app.js',
instances: 'max',
exec_mode: 'cluster',
env: {
NODE_ENV: 'development'
},
env_production: {
NODE_ENV: 'production'
},
max_memory_restart: '1G',
error_file: './logs/err.log',
out_file: './logs/out.log',
log_file: './logs/combined.log'
}]
};
bash
# PM2常用命令
pm2 start app.js # 启动应用
pm2 start ecosystem.config.js # 使用配置文件启动
pm2 list # 列出所有应用
pm2 stop <app_name> # 停止应用
pm2 restart <app_name> # 重启应用
pm2 reload <app_name> # 重载应用
pm2 logs <app_name> # 查看日志
pm2 monit # 监控资源使用
pm2 startup # 设置开机自启
pm2 save # 保存当前进程列表
Clinic.js (性能分析)
bash
# 安装Clinic.js
npm install -g clinic
bash
# 性能分析命令
clinic doctor -- node app.js # 医生诊断
clinic bubbleprof -- node app.js # 分析CPU/IO瓶颈
clinic flame -- node app.js # 火焰图分析
clinic heapprof -- node app.js # 内存分析
调试工具
Node.js内置调试器
bash
# 启动调试模式
node --inspect app.js
node --inspect-brk app.js # 在第一行暂停
node --inspect=0.0.0.0:9229 app.js # 远程调试
# 使用Chrome DevTools调试
# 在Chrome浏览器中访问 chrome://inspect
ndb (Node.js调试器)
bash
# 安装ndb
npm install -g ndb
bash
# 使用ndb调试
ndb app.js
数据库工具
数据库管理工具
Prisma (ORM)
bash
npm install prisma @prisma/client
npx prisma init
javascript
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}
TypeORM
bash
npm install typeorm reflect-metadata mysql2
npm install --save-dev @types/node
javascript
// User Entity
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
email: string;
@Column()
name: string;
}
API开发工具
Swagger/OpenAPI
bash
npm install swagger-jsdoc swagger-ui-express
javascript
// swagger.js
const swaggerJsDoc = require('swagger-jsdoc');
const options = {
definition: {
openapi: '3.0.0',
info: {
title: 'My API',
version: '1.0.0',
},
},
apis: ['./routes/*.js'], // 文件路径
};
const specs = swaggerJsDoc(options);
module.exports = specs;
Postman (API测试)
Postman是一个强大的API开发环境,用于API的开发、测试和文档化。
容器化工具
Docker
text
# Dockerfile示例
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
yaml
# docker-compose.yml示例
version: '3.8'
services:
app:
build: .
ports:
- "3000:3000"
environment:
- NODE_ENV=production
depends_on:
- database
restart: unless-stopped
database:
image: postgres:14
environment:
POSTGRES_DB: myapp
POSTGRES_USER: user
POSTGRES_PASSWORD: password
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
部署工具
CI/CD工具
GitHub Actions
yaml
# .github/workflows/test.yml
name: Test
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [16.x, 18.x]
steps:
- uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- run: npm ci
- run: npm test
Jenkins
Jenkins是一个开源的自动化服务器,用于持续集成和持续部署。
部署平台
- Heroku: 简单的PaaS平台
- AWS: 亚马逊云服务
- Google Cloud Platform: 谷歌云平台
- Microsoft Azure: 微软云平台
- DigitalOcean: 简单易用的云平台
学习资源
官方文档
在线教程
书籍推荐
- "Node.js开发指南" - 郭家宝
- "深入浅出Node.js" - 朴灵
- "Node.js: 服务器端JavaScript精华版" - Tom Hughes-Croucher
社区和论坛
有用的库和模块
Web框架
- Express: 最流行的Node.js Web框架
- Koa: 由Express团队开发的下一代框架
- Fastify: 高性能Web框架
- NestJS: 基于TypeScript的企业级框架
实用工具库
- Lodash: JavaScript实用工具库
- Moment.js / Day.js: 日期处理库
- Axios: HTTP客户端
- Winston: 日志库
- Joi: 数据验证库
- Passport: 认证中间件
数据库相关
- Sequelize: ORM库
- Mongoose: MongoDB ODM
- Knex.js: SQL查询构建器
- Redis: Redis客户端
测试相关
- Jest: 测试框架
- Mocha: 测试框架
- Chai: 断言库
- Sinon: 测试替身库
- Puppeteer: 浏览器自动化工具
这些工具和资源将帮助您更高效地开发、测试和部署Node.js应用程序。