Platform Infrastructure - 8 Core Modules Completed: - Storage Service (LocalAdapter + OSSAdapter stub) - Logging System (Winston + JSON format) - Cache Service (MemoryCache + Redis stub) - Async Job Queue (MemoryQueue + DatabaseQueue stub) - Health Check Endpoints (liveness/readiness/detailed) - Database Connection Pool (with Serverless optimization) - Environment Configuration Management - Monitoring Metrics (DB connections/memory/API) Key Features: - Adapter Pattern for zero-code environment switching - Full backward compatibility with legacy modules - 100% test coverage (all 8 modules verified) - Complete documentation (11 docs updated) Technical Improvements: - Fixed duplicate /health route registration issue - Fixed TypeScript interface export (export type) - Installed winston dependency - Added structured logging with context support - Implemented graceful shutdown for Serverless - Added connection pool optimization for SAE Documentation Updates: - Platform infrastructure planning (04-骞冲彴鍩虹璁炬柦瑙勫垝.md) - Implementation report (2025-11-17-骞冲彴鍩虹璁炬柦瀹炴柦瀹屾垚鎶ュ憡.md) - Verification report (2025-11-17-骞冲彴鍩虹璁炬柦楠岃瘉鎶ュ憡.md) - Git commit guidelines (06-Git鎻愪氦瑙勮寖.md) - Added commit frequency rules - Updated 3 core architecture documents Code Statistics: - New code: 2,532 lines - New files: 22 - Updated files: 130+ - Test pass rate: 100% (8/8 modules) Deployment Readiness: - Local environment: 鉁?Ready - Cloud environment: 馃攧 Needs OSS/Redis dependencies Next Steps: - Ready to start ASL module development - Can directly use storage/logger/cache/jobQueue Tested: Local verification 100% passed Related: #Platform-Infrastructure
5.0 KiB
5.0 KiB
UTF-8 编码最佳实践与中文乱码防范指南
📌 背景
在任务19(后端代码分层)执行过程中,由于 PowerShell 批量操作导致了中文编码问题,引发了多个文件的字符串未闭合、注释代码合并等严重错误,导致服务器无法启动。
🔍 乱码产生的根本原因
1. PowerShell 批量操作的陷阱
# ❌ 错误示例(会导致乱码)
Get-Content file.ts -Raw -Encoding UTF8 |
Set-Content file.ts -NoNewline -Encoding UTF8
问题:
-NoNewline会导致行合并- Windows PowerShell 的 UTF-8 处理不完善
- 可能引入或移除 BOM (Byte Order Mark)
2. 编码不一致
- UTF-8 with BOM vs UTF-8 without BOM
- Windows (CRLF) vs Unix (LF) 行尾符
- 不同编辑器的默认编码设置
✅ 解决方案
方案一:项目配置文件
1. .editorconfig(已创建)
确保所有编辑器统一使用:
- 编码:UTF-8 without BOM
- 行尾符:LF
- 缩进:2空格
2. .gitattributes(已创建)
防止 Git 自动转换行尾符导致的问题。
方案二:VSCode 工作区设置
在项目根目录创建 .vscode/settings.json:
{
"files.encoding": "utf8",
"files.eol": "\n",
"files.insertFinalNewline": true,
"files.trimTrailingWhitespace": true,
"editor.formatOnSave": true
}
方案三:团队规范
强制规则:
-
禁止使用 PowerShell 批量修改代码文件
- 改用 Node.js 脚本
- 使用 IDE 的重构功能
-
所有代码文件必须:
- UTF-8 without BOM
- LF 行尾符
- 文件末尾有空行
-
批量操作前必须:
- Git 提交当前状态
- 在独立分支操作
- 逐步验证,而非一次性全部修改
🛠️ 安全的批量修改方案
使用 Node.js 脚本(推荐)
const fs = require('fs');
const path = require('path');
function safeReplace(filePath, searchValue, replaceValue) {
try {
// 使用 UTF-8 读取
let content = fs.readFileSync(filePath, 'utf8');
// 确认需要修改
if (!content.includes(searchValue)) {
return false;
}
// 执行替换
const newContent = content.replace(
new RegExp(searchValue, 'g'),
replaceValue
);
// 写回(保持原有行尾符)
fs.writeFileSync(filePath, newContent, 'utf8');
console.log(`✅ 修改成功: ${path.basename(filePath)}`);
return true;
} catch (error) {
console.error(`❌ 修改失败: ${filePath}`, error.message);
return false;
}
}
使用 TypeScript 编辑器 API(最安全)
// 使用 ts-morph 库进行安全的代码重构
import { Project } from 'ts-morph';
const project = new Project({
tsConfigFilePath: "tsconfig.json",
});
// 遍历所有源文件
project.getSourceFiles().forEach(sourceFile => {
// 使用 AST 级别的重构,不会破坏编码
sourceFile.getImportDeclarations().forEach(importDecl => {
const moduleSpecifier = importDecl.getModuleSpecifierValue();
if (moduleSpecifier.startsWith('../config/')) {
importDecl.setModuleSpecifier(
moduleSpecifier.replace('../config/', '@config/')
);
}
});
sourceFile.saveSync();
});
🚨 发现乱码后的处理流程
1. 立即停止操作
git status # 查看影响范围
2. 恢复备份
git restore . # 或从手动备份恢复
3. 使用安全方案重新执行
4. 验证
# 编译检查
npm run build
# 启动测试
npm run dev
📝 检查清单
在提交代码前,确保:
- 所有
.ts文件编码为 UTF-8 - 没有 BOM 标记
- 使用 LF 行尾符
- 没有乱码字符(<EFBFBD>)
- 字符串都正确闭合
- 注释没有和代码行合并
- 编译通过(
npm run build) - 服务器可以启动(
npm run dev)
🔧 实用工具命令
检测文件编码
file -bi <filename> # Linux/Mac
转换编码
iconv -f GBK -t UTF-8 file.txt > file_utf8.txt
检查 BOM
# Linux/Mac
head -c 3 file.txt | od -A n -t x1
# 如果输出 ef bb bf,则有 BOM
移除 BOM
# Linux/Mac
sed -i '1s/^\xEF\xBB\xBF//' file.txt
💡 经验教训
-
架构优先,工具其次
- 正确的架构设计可以减少批量修改的需求
-
小步快跑,频繁验证
- 每修改一个文件就测试一次
- 不要一次性修改所有文件
-
自动化测试是最后防线
- 编译检查
- Linter 检查
- 单元测试
-
备份是安全的保障
- Git 提交
- 手动备份关键目录
- 云端同步
📚 参考资料
文档版本: 1.0
创建日期: 2025-11-14
最后更新: 2025-11-14
维护人员: AI Assistant