开发示例
🟢 Node.js 项目开发
用 Trae 构建 Node.js 后端服务,从 Express API 到命令行工具,AI 帮你写更好的代码。
示例一:Express + TypeScript API
Terminal — 项目初始化
mkdir node-api && cd node-api
npm init -y
npm install express cors
npm install -D typescript @types/node @types/express ts-node nodemon
npx tsc --init
trae .
Express 中间件 + 路由架构
Express + TypeScriptsrc/app.ts
import express, { Request, Response, NextFunction } from 'express'
import cors from 'cors'
const app = express()
// 中间件
app.use(cors())
app.use(express.json())
app.use(requestLogger)
// 请求日志中间件
function requestLogger(req: Request, res: Response, next: NextFunction) {
const start = Date.now()
res.on('finish', () => {
const ms = Date.now() - start
console.log(`${req.method} ${req.path} ${res.statusCode} ${ms}ms`)
})
next()
}
// 路由
const router = express.Router()
const items: { id: number; name: string; value: number }[] = []
let nextId = 1
router.get('/', (req, res) => {
const { sort, order = 'asc' } = req.query
let result = [...items]
if (sort === 'value') {
result.sort((a, b) => order === 'asc' ? a.value - b.value : b.value - a.value)
}
res.json({ data: result, total: result.length })
})
router.post('/', (req, res) => {
const { name, value } = req.body
if (!name || value === undefined) {
return res.status(400).json({ error: 'name 和 value 必填' })
}
const item = { id: nextId++, name, value: Number(value) }
items.push(item)
res.status(201).json(item)
})
router.delete('/:id', (req, res) => {
const id = Number(req.params.id)
const idx = items.findIndex(i => i.id === id)
if (idx === -1) return res.status(404).json({ error: '不存在' })
items.splice(idx, 1)
res.status(204).send()
})
app.use('/api/items', router)
// 全局错误处理
app.use((err: Error, req: Request, res: Response, _next: NextFunction) => {
console.error(err)
res.status(500).json({ error: '服务器内部错误' })
})
app.listen(3000, () => console.log('🚀 服务运行在 http://localhost:3000'))
export default app
示例二:命令行工具 (CLI)
cli.js — 文件批量重命名工具
#!/usr/bin/env node
const fs = require('fs')
const path = require('path')
const [,, dir = '.', pattern = '', replacement = ''] = process.argv
if (!pattern) {
console.log('用法: node cli.js [目录] [查找] [替换]')
console.log('示例: node cli.js ./images IMG img')
process.exit(0)
}
const files = fs.readdirSync(dir)
let count = 0
files.forEach(file => {
if (!file.includes(pattern)) return
const newName = file.replaceAll(pattern, replacement)
fs.renameSync(path.join(dir, file), path.join(dir, newName))
console.log(`✓ ${file} → ${newName}`)
count++
})
console.log(`\n完成:重命名了 ${count} 个文件`)
示例三:WebSocket 实时通信
ws-server.js
const { WebSocketServer } = require('ws')
const wss = new WebSocketServer({ port: 8080 })
const clients = new Map()
wss.on('connection', (ws) => {
const id = Date.now().toString(36)
clients.set(id, ws)
console.log(`客户端 ${id} 已连接,当前 ${clients.size} 人在线`)
// 广播上线通知
broadcast({ type: 'join', id, online: clients.size }, id)
ws.on('message', (data) => {
try {
const msg = JSON.parse(data.toString())
broadcast({ ...msg, from: id, time: new Date().toISOString() })
} catch { /* 忽略非 JSON 消息 */ }
})
ws.on('close', () => {
clients.delete(id)
broadcast({ type: 'leave', id, online: clients.size })
})
})
function broadcast(data, excludeId = null) {
const msg = JSON.stringify(data)
clients.forEach((ws, id) => {
if (id !== excludeId && ws.readyState === 1) ws.send(msg)
})
}
console.log('WebSocket 服务运行在 ws://localhost:8080')
在 Trae 中开发 Node.js 时,安装 REST Client 插件,可以直接在 .http 文件中测试 API,无需切换到 Postman。