一、TypeScript在Node.js中的核心價值
1.1 靜態類型檢測
function add ( a: number , b: string ) { return a + b
}
1.2 工具鏈增強
npm install --save-dev typescript @types/node ts-node tsconfig.json
1.3 代碼維護性提升
interface User { id: number name: string email: string
} function createUser ( user: User) {
}
二、框架選型對比:Express vs Fastify
2.1 核心特性對比
維度 Express Fastify 性能 每秒處理約5000請求 每秒處理約15000請求 代碼侵入性 需要中間件鏈 單文件配置 社區支持 90萬+ GitHub Star 40萬+ GitHub Star TypeScript支持 完整但需手動配置 內置TypeScript模板
2.2 性能測試數據
基準測試環境
16核CPU/32GB內存
1000并發請求
Express: 2.1s響應延遲
Fastify: 0.7s響應延遲
三、TypeScript框架實戰配置
3.1 Express+TypeScript快速搭建
{ "compilerOptions" : { "target" : "ES2020" , "module" : "commonjs" , "strict" : true , "outDir" : "./dist" } , "include" : [ "src/**/*" ]
}
import express from 'express' ;
import { User } from './models/user' ; const app = express ( ) ;
app. get ( '/users' , ( req: Request, res: Response) => { res. json ( { users: User. find ( ) } ) ;
} ) ; app. listen ( 3000 ) ;
3.2 Fastify+TypeScript配置
{ "compilerOptions" : { "target" : "ES2020" , "module" : "commonjs" , "strict" : true , "types" : [ "node" , "fastify" ] }
}
import fastify from 'fastify' ; const app = fastify ( ) ; app. get < { Querystring: { id: number }
} > ( '/users' , async ( req, res) => { const user = await User. findById ( req. query. id) ; return user;
} ) ; app. listen ( { port: 3000 } ) ;
四、核心功能對比實戰
4.1 路由系統對比
app. get ( '/api/users' , ( req, res) => { res. send ( users) ;
} ) ;
@Route ( '/api/users' )
export class UserController { @Get ( ) async getAll ( ) { return User. find ( ) ; }
}
4.2 中間件性能測試
app. use ( bodyParser. json ( ) ) ;
app. use ( cors ( ) ) ;
app. use ( mongoSanitize ( ) ) ;
app. use ( helmet ( ) ) ;
fastify. register ( require ( '@fastify/cors' ) , { origin: true
} ) ;
五、適用場景深度分析
5.1 選擇Express的場景
import { NestFactory } from '@nestjs/core' ;
import { AppModule } from './app.module' ; async function bootstrap ( ) { const app = await NestFactory. create ( AppModule) ; await app. listen ( 3000 ) ;
}
bootstrap ( ) ;
5.2 Fastify的極致性能場景
const server = fastify ( ) ; server. get ( '/realtime' , async ( request, reply ) => { const data = await realTimeDataProcessor ( ) ; reply. header ( 'Content-Type' , 'text/event-stream' ) . send ( data) ;
} ) ;
六、性能優化實戰
6.1 內存占用對比
node --expose-gc build/app.js
// 使用128MB內存
node --expose-gc build/app.js
// 使用64MB內存
6.2 壓力測試腳本
artillery run config.yml
config : target : "http://localhost:3000"
scenarios : - flow : - get : url : "/api/users" duration : 60 arrivalRate : 100
七、常見問題解決方案
7.1 類型推斷問題
const arr = [ 1 , 2 , 3 ] ;
arr. push ( "test" ) ;
const arr: number [ ] = [ 1 , 2 , 3 ] ;
7.2 框架兼容性問題
npm install @fastify/express
import fastify from 'fastify' ;
import { json } from 'express' ; const app = fastify ( ) ;
app. register ( require ( '@fastify/express' ) ) ;
app. use ( json ( ) ) ;
八、總結與選型建議
8.1 選型決策樹
小規模
中大型
項目規模
選擇Fastify
選擇Express/NestJS
關注性能優化
需要復雜模塊化
8.2 最佳實踐
npm run build
npm run watch
npm run test