Fastify安装 #

一、安装前的准备 #

在安装Fastify之前,我们需要确保Node.js环境已正确配置。

1.1 系统要求 #

要求 版本
Node.js >= 18.x (推荐LTS)
npm >= 8.x
操作系统 Windows/macOS/Linux

1.2 检查Node.js环境 #

bash
node --version
npm --version

预期输出:

text
v20.11.0
10.2.4

二、安装Node.js #

2.1 macOS安装 #

方法一:Homebrew(推荐)

bash
brew install node@20

方法二:nvm(版本管理)

bash
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
source ~/.zshrc

nvm install 20
nvm use 20
nvm alias default 20

2.2 Windows安装 #

方法一:官方安装包

  1. 访问 Node.js官网
  2. 下载LTS版本安装包
  3. 运行安装程序

方法二:Chocolatey

powershell
choco install nodejs-lts

方法三:nvm-windows

powershell
nvm install 20
nvm use 20

2.3 Linux安装 #

Ubuntu/Debian:

bash
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs

CentOS/RHEL:

bash
curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash -
sudo yum install -y nodejs

三、创建Fastify项目 #

3.1 使用Fastify CLI(推荐) #

Fastify提供了官方CLI工具来快速创建项目:

bash
npm install -g fastify-cli

fastify generate my-fastify-app

cd my-fastify-app

npm install

生成的项目结构:

text
my-fastify-app/
├── app.js
├── package.json
├── plugins/
│   ├── README.md
│   ├── sensible.js
│   └── support.js
├── routes/
│   ├── README.md
│   ├── example/
│   │   └── index.js
│   └── root.js
└── test/
    ├── helper.js
    └── test.js

3.2 手动创建项目 #

步骤一:创建项目目录

bash
mkdir my-fastify-app
cd my-fastify-app
npm init -y

步骤二:安装Fastify

bash
npm install fastify

步骤三:创建入口文件

创建 app.js

javascript
const fastify = require('fastify')({
  logger: true
})

fastify.get('/', async (request, reply) => {
  return { hello: 'world' }
})

const start = async () => {
  try {
    await fastify.listen({ port: 3000 })
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}

start()

步骤四:添加启动脚本

编辑 package.json

json
{
  "name": "my-fastify-app",
  "version": "1.0.0",
  "scripts": {
    "start": "node app.js",
    "dev": "node --watch app.js"
  },
  "dependencies": {
    "fastify": "^4.26.0"
  }
}

四、开发环境配置 #

4.1 开发依赖安装 #

bash
npm install -D nodemon
npm install -D dotenv

更新 package.json

json
{
  "scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js",
    "dev:watch": "node --watch app.js"
  }
}

4.2 环境变量配置 #

创建 .env 文件:

env
NODE_ENV=development
PORT=3000
HOST=0.0.0.0
LOG_LEVEL=debug

创建 .env.example

env
NODE_ENV=development
PORT=3000
HOST=0.0.0.0
LOG_LEVEL=info

安装dotenv:

bash
npm install dotenv

更新 app.js

javascript
require('dotenv').config()

const fastify = require('fastify')({
  logger: {
    level: process.env.LOG_LEVEL
  }
})

fastify.get('/', async (request, reply) => {
  return { hello: 'world' }
})

const start = async () => {
  try {
    await fastify.listen({
      port: process.env.PORT || 3000,
      host: process.env.HOST || '0.0.0.0'
    })
    console.log(`Server running at http://${process.env.HOST}:${process.env.PORT}`)
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}

start()

4.3 TypeScript支持 #

安装TypeScript依赖:

bash
npm install -D typescript @types/node tsx
npx tsc --init

创建 tsconfig.json

json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "lib": ["ES2022"],
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

创建 src/app.ts

typescript
import Fastify from 'fastify'

const fastify = Fastify({
  logger: true
})

fastify.get('/', async (request, reply) => {
  return { hello: 'world' }
})

const start = async () => {
  try {
    await fastify.listen({ port: 3000 })
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}

start()

更新 package.json

json
{
  "type": "module",
  "scripts": {
    "build": "tsc",
    "start": "node dist/app.js",
    "dev": "tsx watch src/app.ts"
  }
}

五、开发工具推荐 #

5.1 编辑器/IDE #

工具 特点 适用人群
VS Code 免费、插件丰富 大多数开发者
WebStorm JetBrains出品、功能强大 专业开发
Sublime Text 轻量快速 喜欢简洁的开发者

5.2 VS Code插件推荐 #

  • ESLint:代码规范检查
  • Prettier:代码格式化
  • Thunder Client:API测试
  • DotENV:环境变量支持
  • JavaScript and TypeScript Nightly:最新语法支持

5.3 ESLint配置 #

bash
npm install -D eslint @eslint/js
npx eslint --init

创建 eslint.config.mjs

javascript
import js from '@eslint/js'

export default [
  js.configs.recommended,
  {
    rules: {
      'no-unused-vars': 'warn',
      'no-console': 'off'
    }
  }
]

六、常用插件安装 #

6.1 核心插件 #

bash
npm install @fastify/cors
npm install @fastify/helmet
npm install @fastify/cookie
npm install @fastify/jwt
npm install @fastify/static
npm install @fastify/multipart

6.2 开发插件 #

bash
npm install @fastify/swagger
npm install @fastify/swagger-ui
npm install @fastify/rate-limit

6.3 数据库插件 #

bash
npm install @fastify/mongodb
npm install @fastify/postgres
npm install @fastify/redis

七、验证安装 #

7.1 启动服务器 #

bash
npm run dev

7.2 测试请求 #

bash
curl http://localhost:3000

预期输出:

json
{"hello":"world"}

7.3 检查日志 #

text
{"level":30,"time":1709500000000,"pid":12345,"hostname":"localhost","reqId":"req-1","req":{"method":"GET","url":"/","host":"localhost:3000"},"msg":"incoming request"}
{"level":30,"time":1709500000001,"pid":12345,"hostname":"localhost","reqId":"req-1","res":{"statusCode":200},"responseTime":1.234,"msg":"request completed"}

八、常见问题 #

8.1 端口被占用 #

问题:EADDRINUSE错误

解决

bash
lsof -i :3000
kill -9 <PID>

PORT=3001 npm run dev

8.2 模块找不到 #

问题:Cannot find module ‘fastify’

解决

bash
rm -rf node_modules package-lock.json
npm install

8.3 TypeScript类型错误 #

问题:类型定义缺失

解决

bash
npm install -D @types/node

九、项目配置最佳实践 #

9.1 推荐目录结构 #

text
my-fastify-app/
├── src/
│   ├── app.ts
│   ├── config/
│   │   └── index.ts
│   ├── plugins/
│   │   ├── database.ts
│   │   └── auth.ts
│   ├── routes/
│   │   ├── index.ts
│   │   └── users.ts
│   ├── schemas/
│   │   └── user.ts
│   └── utils/
│       └── helpers.ts
├── test/
│   └── app.test.ts
├── .env
├── .env.example
├── package.json
└── tsconfig.json

9.2 package.json配置 #

json
{
  "name": "my-fastify-app",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "build": "tsc",
    "start": "node dist/app.js",
    "dev": "tsx watch src/app.ts",
    "test": "node --test",
    "lint": "eslint src/**/*.ts"
  },
  "dependencies": {
    "fastify": "^4.26.0",
    "@fastify/cors": "^9.0.0",
    "@fastify/helmet": "^11.0.0",
    "dotenv": "^16.4.0"
  },
  "devDependencies": {
    "@types/node": "^20.11.0",
    "typescript": "^5.3.0",
    "tsx": "^4.7.0",
    "eslint": "^8.56.0"
  }
}

十、总结 #

本章我们学习了:

  1. Node.js安装:各平台安装方法
  2. Fastify安装:CLI和手动创建项目
  3. 开发环境:TypeScript、ESLint配置
  4. 常用插件:核心插件安装
  5. 项目结构:最佳实践目录结构

安装完成后,让我们进入下一章,编写第一个Fastify应用!

最后更新:2026-03-28