server.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. // PNG 序列动画预览工具 - 服务器主文件
  2. // 负责启动 HTTP 服务器和静态文件服务
  3. const http = require('http');
  4. const fs = require('fs');
  5. const path = require('path');
  6. const url = require('url');
  7. const TextureReader = require('./texture-reader');
  8. const ZipHandler = require('./zip');
  9. const DiskManager = require('./disk');
  10. const ReplaceCharacterHandler = require('./replace-character');
  11. const RemoveBackgroundBase64 = require('./remove-background-base64');
  12. const { handleLoginRequest, handleCheckPhoneRequest } = require('./login');
  13. const { handleRegisterRequest } = require('./register');
  14. const PORT = 3000;
  15. const SERVER_DIR = __dirname; // Server 目录
  16. const CLIENT_DIR = path.join(__dirname, '..', 'Client'); // Client 目录
  17. const ADMIN_DIR = path.join(__dirname, '..', 'admin'); // Admin 目录
  18. // MIME 类型映射
  19. const mimeTypes = {
  20. '.html': 'text/html',
  21. '.js': 'text/javascript',
  22. '.css': 'text/css',
  23. '.png': 'image/png',
  24. '.jpg': 'image/jpeg',
  25. '.gif': 'image/gif',
  26. '.json': 'application/json',
  27. };
  28. // 初始化 TextureReader
  29. const textureReader = new TextureReader(SERVER_DIR);
  30. // 初始化 DiskManager
  31. const diskManager = new DiskManager();
  32. // 初始化 StoreManager
  33. const StoreManager = require('./store/store');
  34. const storeManager = new StoreManager();
  35. // 初始化 Pay 模块
  36. const { handlePurchaseRequest, handleGetPurchaseHistory } = require('./pay');
  37. // 创建 HTTP 服务器
  38. const server = http.createServer((req, res) => {
  39. const parsedUrl = url.parse(req.url, true);
  40. let pathname = parsedUrl.pathname;
  41. // 添加 CORS 头(允许 file:// 协议访问)
  42. res.setHeader('Access-Control-Allow-Origin', '*');
  43. res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  44. res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  45. // 处理 OPTIONS 预检请求
  46. if (req.method === 'OPTIONS') {
  47. res.writeHead(200);
  48. res.end();
  49. return;
  50. }
  51. // 调试日志:记录所有API请求
  52. if (pathname.startsWith('/api/')) {
  53. console.log(`[Server] ${req.method} ${pathname}`);
  54. }
  55. // API: 获取可用的文件夹列表
  56. if (pathname === '/api/folders') {
  57. textureReader.handleGetFolders(res);
  58. return;
  59. }
  60. // API: 获取指定文件夹中的帧文件列表
  61. if (pathname.startsWith('/api/frames/')) {
  62. const parsedUrl = url.parse(req.url, true);
  63. const encodedPath = pathname.replace('/api/frames/', '');
  64. // 对路径的每一段进行解码
  65. const folderName = encodedPath.split('/').map(seg => decodeURIComponent(seg)).join('/');
  66. const username = parsedUrl.query.username; // 从查询参数获取用户名
  67. console.log('[Server] API请求帧列表, 原始:', encodedPath, '解码后:', folderName, '用户名:', username);
  68. // 如果有用户名,尝试从用户网盘查找
  69. if (username) {
  70. const { handleGetUserFrames } = require('./disk');
  71. diskManager.handleGetUserFrames(username, folderName, res);
  72. } else {
  73. // 回退到旧的 TextureReader(兼容旧代码)
  74. textureReader.handleGetFrames(folderName, res);
  75. }
  76. return;
  77. }
  78. // API: 打包 sprite sheet 为 ZIP
  79. if (pathname === '/api/pack') {
  80. ZipHandler.handlePackRequest(req, res);
  81. return;
  82. }
  83. // API: 角色替换(图生图)- 旧版本,保留兼容
  84. if (pathname === '/api/replace-character') {
  85. ReplaceCharacterHandler.handleReplaceRequest(req, res);
  86. return;
  87. }
  88. // API: AI生图(队列版本)
  89. if (pathname === '/api/ai/generate') {
  90. const { handleAIRequest } = require('./ai-queue');
  91. handleAIRequest(req, res);
  92. return;
  93. }
  94. // API: AI生图重试(免费)
  95. if (pathname === '/api/ai/retry' && req.method === 'POST') {
  96. const { handleRetryRequest } = require('./ai-queue');
  97. handleRetryRequest(req, res);
  98. return;
  99. }
  100. // API: 获取AI生成的图片
  101. if (pathname === '/api/ai/image') {
  102. const parsedUrl = require('url').parse(req.url, true);
  103. const { username, id } = parsedUrl.query;
  104. if (!username || !id) {
  105. res.writeHead(400, { 'Content-Type': 'text/plain' });
  106. res.end('Missing parameters');
  107. return;
  108. }
  109. try {
  110. const fs = require('fs');
  111. const path = require('path');
  112. const usersDir = path.join(__dirname, 'users');
  113. const userDir = path.join(usersDir, username.toLowerCase());
  114. const aiDir = path.join(userDir, 'ai-images');
  115. const imagePath = path.join(aiDir, `${id}.png`);
  116. // 安全检查
  117. const normalizedPath = path.normalize(imagePath);
  118. const normalizedAiDir = path.normalize(aiDir);
  119. if (!normalizedPath.startsWith(normalizedAiDir)) {
  120. res.writeHead(403, { 'Content-Type': 'text/plain' });
  121. res.end('Access denied');
  122. return;
  123. }
  124. if (fs.existsSync(imagePath)) {
  125. const imageData = fs.readFileSync(imagePath);
  126. res.writeHead(200, {
  127. 'Content-Type': 'image/png',
  128. 'Access-Control-Allow-Origin': '*',
  129. 'Cache-Control': 'public, max-age=3600'
  130. });
  131. res.end(imageData);
  132. } else {
  133. res.writeHead(404, { 'Content-Type': 'text/plain' });
  134. res.end('Image not found');
  135. }
  136. } catch (error) {
  137. console.error('[Server] 获取AI图片失败:', error);
  138. res.writeHead(500, { 'Content-Type': 'text/plain' });
  139. res.end('Internal server error');
  140. }
  141. return;
  142. }
  143. // API: 获取AI生成预览图(原始texture)
  144. if (pathname === '/api/ai/preview') {
  145. const parsedUrl = require('url').parse(req.url, true);
  146. const { username, id } = parsedUrl.query;
  147. if (!username || !id) {
  148. res.writeHead(400, { 'Content-Type': 'text/plain' });
  149. res.end('Missing parameters');
  150. return;
  151. }
  152. try {
  153. const fs = require('fs');
  154. const path = require('path');
  155. const usersDir = path.join(__dirname, 'users');
  156. const userDir = path.join(usersDir, username.toLowerCase());
  157. const aiDir = path.join(userDir, 'ai-images');
  158. const imagePath = path.join(aiDir, `${id}_preview.png`);
  159. // 安全检查
  160. const normalizedPath = path.normalize(imagePath);
  161. const normalizedAiDir = path.normalize(aiDir);
  162. if (!normalizedPath.startsWith(normalizedAiDir)) {
  163. res.writeHead(403, { 'Content-Type': 'text/plain' });
  164. res.end('Access denied');
  165. return;
  166. }
  167. if (fs.existsSync(imagePath)) {
  168. const imageData = fs.readFileSync(imagePath);
  169. res.writeHead(200, {
  170. 'Content-Type': 'image/png',
  171. 'Access-Control-Allow-Origin': '*',
  172. 'Cache-Control': 'public, max-age=3600'
  173. });
  174. res.end(imageData);
  175. } else {
  176. res.writeHead(404, { 'Content-Type': 'text/plain' });
  177. res.end('Preview not found');
  178. }
  179. } catch (error) {
  180. console.error('[Server] 获取AI预览图失败:', error);
  181. res.writeHead(500, { 'Content-Type': 'text/plain' });
  182. res.end('Internal server error');
  183. }
  184. return;
  185. }
  186. // API: Base64 图片抠图
  187. if (pathname === '/api/remove-background-base64') {
  188. RemoveBackgroundBase64.handleRequest(req, res);
  189. return;
  190. }
  191. // API: 普通抠图(使用 image-matting.py)
  192. if (pathname === '/api/matting-normal') {
  193. const MattingNormal = require('./matting-normal');
  194. MattingNormal.handleRequest(req, res);
  195. return;
  196. }
  197. // API: VIP抠图(使用 BiRefNet)
  198. if (pathname === '/api/matting-vip') {
  199. const MattingVIP = require('./matting-vip');
  200. MattingVIP.handleRequest(req, res);
  201. return;
  202. }
  203. // API: 网盘 - 获取文件列表
  204. if (pathname === '/api/disk/list') {
  205. diskManager.handleListRequest(req, res);
  206. return;
  207. }
  208. // API: 网盘 - 上传文件
  209. if (pathname === '/api/disk/upload') {
  210. diskManager.handleUploadRequest(req, res);
  211. return;
  212. }
  213. // API: 网盘 - 创建文件夹
  214. if (pathname === '/api/disk/create-folder') {
  215. diskManager.handleCreateFolderRequest(req, res);
  216. return;
  217. }
  218. // API: 网盘 - 下载文件
  219. if (pathname === '/api/disk/download') {
  220. diskManager.handleDownloadRequest(req, res);
  221. return;
  222. }
  223. // API: 网盘 - 重命名
  224. if (pathname === '/api/disk/rename') {
  225. diskManager.handleRenameRequest(req, res);
  226. return;
  227. }
  228. // API: 网盘 - 图片预览
  229. if (pathname === '/api/disk/preview') {
  230. diskManager.handlePreviewRequest(req, res);
  231. return;
  232. }
  233. // API: 网盘 - 移动文件/文件夹
  234. if (pathname === '/api/disk/move') {
  235. diskManager.handleMoveRequest(req, res);
  236. return;
  237. }
  238. // API: 网盘 - 复制文件/文件夹
  239. if (pathname === '/api/disk/copy') {
  240. diskManager.handleCopyRequest(req, res);
  241. return;
  242. }
  243. // API: 网盘 - 删除文件/文件夹
  244. if (pathname === '/api/disk/delete') {
  245. diskManager.handleDeleteRequest(req, res);
  246. return;
  247. }
  248. // API: 网盘 - 一键抠背景
  249. if (pathname === '/api/disk/remove-background') {
  250. diskManager.handleRemoveBackgroundRequest(req, res);
  251. return;
  252. }
  253. // API: 网盘 - 剪裁最小区域
  254. if (pathname === '/api/disk/crop-mini') {
  255. diskManager.handleCropMiniRequest(req, res);
  256. return;
  257. }
  258. // API: 用户注册
  259. if (pathname === '/api/register') {
  260. handleRegisterRequest(req, res);
  261. return;
  262. }
  263. // API: 用户登录
  264. if (pathname === '/api/login') {
  265. handleLoginRequest(req, res);
  266. return;
  267. }
  268. // API: 检查手机号是否存在
  269. if (pathname === '/api/check-phone') {
  270. handleCheckPhoneRequest(req, res);
  271. return;
  272. }
  273. // API: 获取用户点数
  274. if (pathname === '/api/user/points') {
  275. const { handleGetUserPoints } = require('./user');
  276. handleGetUserPoints(req, res);
  277. return;
  278. }
  279. // API: 扣除用户点数
  280. if (pathname === '/api/user/deduct-points' && req.method === 'POST') {
  281. const { handleDeductUserPoints } = require('./user');
  282. handleDeductUserPoints(req, res);
  283. return;
  284. }
  285. // API: 获取用户信息
  286. if (pathname === '/api/user/info') {
  287. const { handleGetUserInfo } = require('./user');
  288. handleGetUserInfo(req, res);
  289. return;
  290. }
  291. // API: 更新用户信息
  292. if (pathname === '/api/user/update') {
  293. const { handleUpdateUser } = require('./user');
  294. handleUpdateUser(req, res);
  295. return;
  296. }
  297. // API: 上传头像
  298. if (pathname === '/api/user/avatar') {
  299. const { handleUploadAvatar } = require('./user');
  300. handleUploadAvatar(req, res);
  301. return;
  302. }
  303. // API: 获取AI生图历史
  304. if (pathname === '/api/ai/history') {
  305. const { handleGetAIHistory } = require('./user');
  306. handleGetAIHistory(req, res);
  307. return;
  308. }
  309. // API: 充值
  310. if (pathname === '/api/recharge') {
  311. const { handleRecharge } = require('./user');
  312. handleRecharge(req, res);
  313. return;
  314. }
  315. // API: 管理后台 - 获取所有用户
  316. if (pathname === '/api/admin/users') {
  317. const { handleGetAllUsers } = require('./admin');
  318. handleGetAllUsers(req, res);
  319. return;
  320. }
  321. // API: 管理后台 - 更新用户
  322. if (pathname === '/api/admin/users/update') {
  323. const { handleAdminUpdateUser } = require('./admin');
  324. handleAdminUpdateUser(req, res);
  325. return;
  326. }
  327. // API: 管理后台 - 上传商店素材
  328. if (pathname === '/api/admin/store/upload') {
  329. const { handleAdminUploadStore } = require('./admin');
  330. handleAdminUploadStore(req, res);
  331. return;
  332. }
  333. // API: 管理后台 - 删除商店素材
  334. if (pathname === '/api/admin/store/delete') {
  335. console.log('[Server] 处理删除请求');
  336. const { handleAdminDeleteStore } = require('./admin');
  337. handleAdminDeleteStore(req, res);
  338. // 清除分类缓存(删除可能影响分类列表)
  339. storeManager.clearCategoriesCache();
  340. return;
  341. }
  342. // API: 管理后台 - 创建分类文件夹
  343. if (pathname === '/api/admin/store/create-folder') {
  344. const { handleAdminCreateFolder } = require('./admin');
  345. handleAdminCreateFolder(req, res);
  346. // 清除分类缓存
  347. storeManager.clearCategoriesCache();
  348. return;
  349. }
  350. // API: 管理后台 - 重命名商店素材
  351. if (pathname === '/api/admin/store/rename') {
  352. const { handleAdminRenameStore } = require('./admin');
  353. handleAdminRenameStore(req, res);
  354. // 清除分类缓存(重命名可能影响分类列表)
  355. storeManager.clearCategoriesCache();
  356. return;
  357. }
  358. // API: 管理后台 - 更新资源价格
  359. if (pathname === '/api/admin/store/update-price') {
  360. const { handleAdminUpdatePrice } = require('./admin');
  361. handleAdminUpdatePrice(req, res);
  362. // 清除价格缓存
  363. storeManager.clearPricesCache();
  364. return;
  365. }
  366. // API: 管理后台 - 获取货币设置
  367. if (pathname === '/api/admin/currency/settings' && req.method === 'GET') {
  368. const { handleGetCurrencySettings } = require('./admin');
  369. handleGetCurrencySettings(req, res);
  370. return;
  371. }
  372. // API: 管理后台 - 保存货币设置
  373. if (pathname === '/api/admin/currency/settings' && req.method === 'POST') {
  374. const { handleSaveCurrencySettings } = require('./admin');
  375. handleSaveCurrencySettings(req, res);
  376. return;
  377. }
  378. // API: 管理后台 - 获取商品定价设置
  379. if (pathname === '/api/admin/product-pricing/settings' && req.method === 'GET') {
  380. const { handleGetProductPricingSettings } = require('./admin');
  381. handleGetProductPricingSettings(req, res);
  382. return;
  383. }
  384. // API: 管理后台 - 保存商品定价设置
  385. if (pathname === '/api/admin/product-pricing/settings' && req.method === 'POST') {
  386. const { handleSaveProductPricingSettings } = require('./admin');
  387. handleSaveProductPricingSettings(req, res);
  388. return;
  389. }
  390. // API: 客户端 - 获取商品定价(用于显示价格)
  391. if (pathname === '/api/product-pricing' && req.method === 'GET') {
  392. const { handleGetProductPricingSettings } = require('./admin');
  393. handleGetProductPricingSettings(req, res);
  394. return;
  395. }
  396. // API: 管理后台 - 更新分类排序
  397. if (pathname === '/api/admin/store/update-order') {
  398. let body = '';
  399. req.on('data', chunk => { body += chunk.toString(); });
  400. req.on('end', async () => {
  401. try {
  402. const data = JSON.parse(body);
  403. const { order } = data;
  404. if (!order || !Array.isArray(order)) {
  405. res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
  406. res.end(JSON.stringify({ success: false, message: '缺少排序数据' }));
  407. return;
  408. }
  409. const success = await storeManager.saveCategoryOrder(order);
  410. if (success) {
  411. res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
  412. res.end(JSON.stringify({ success: true, message: '排序已保存' }));
  413. } else {
  414. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  415. res.end(JSON.stringify({ success: false, message: '保存排序失败' }));
  416. }
  417. } catch (error) {
  418. console.error('[Server] 更新分类排序失败:', error);
  419. res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
  420. res.end(JSON.stringify({ success: false, message: error.message }));
  421. }
  422. });
  423. return;
  424. }
  425. // API: 商店 - 获取分类列表
  426. if (pathname === '/api/store/categories') {
  427. storeManager.handleGetCategories(req, res);
  428. return;
  429. }
  430. // API: 商店 - 获取资源列表
  431. if (pathname === '/api/store/resources') {
  432. storeManager.handleGetResources(req, res);
  433. return;
  434. }
  435. // API: 商店 - 预览图
  436. if (pathname === '/api/store/preview') {
  437. storeManager.handlePreview(req, res);
  438. return;
  439. }
  440. // API: 商店 - 获取帧列表
  441. if (pathname === '/api/store/frames') {
  442. storeManager.handleGetFrames(req, res);
  443. return;
  444. }
  445. // API: 商店 - 获取帧图片
  446. if (pathname === '/api/store/frame') {
  447. storeManager.handleGetFrame(req, res);
  448. return;
  449. }
  450. // API: 支付 - 购买资源
  451. if (pathname === '/api/pay/purchase') {
  452. handlePurchaseRequest(req, res);
  453. return;
  454. }
  455. // API: 支付 - 检查资源是否存在
  456. if (pathname === '/api/pay/check-resource') {
  457. const { handleCheckResourceRequest } = require('./pay');
  458. handleCheckResourceRequest(req, res);
  459. return;
  460. }
  461. // API: 获取用户购买记录
  462. if (pathname === '/api/pay/purchase-history' && req.method === 'GET') {
  463. handleGetPurchaseHistory(req, res);
  464. return;
  465. }
  466. // API: 获取默认头像列表
  467. if (pathname === '/api/avatars/default') {
  468. const fs = require('fs');
  469. const avatarDir = path.join(__dirname, 'avatar');
  470. fs.readdir(avatarDir, (err, files) => {
  471. if (err) {
  472. res.writeHead(500, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
  473. res.end(JSON.stringify({ success: false, error: '读取头像目录失败' }));
  474. return;
  475. }
  476. // 过滤出图片文件
  477. const imageFiles = files.filter(file => {
  478. const ext = path.extname(file).toLowerCase();
  479. return ['.png', '.jpg', '.jpeg', '.gif'].includes(ext);
  480. });
  481. // 返回头像文件名列表
  482. res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
  483. res.end(JSON.stringify({ success: true, avatars: imageFiles }));
  484. });
  485. return;
  486. }
  487. // 处理 favicon.ico 请求,重定向到 static/favicon.png
  488. if (pathname === '/favicon.ico') {
  489. pathname = '/static/favicon.png';
  490. }
  491. // 默认首页 - 跳转到管理后台
  492. if (pathname === '/') {
  493. res.writeHead(302, { 'Location': '/admin/index.html' });
  494. res.end();
  495. return;
  496. }
  497. // /admin 路径也跳转到管理后台
  498. if (pathname === '/admin' || pathname === '/admin/') {
  499. res.writeHead(302, { 'Location': '/admin/index.html' });
  500. res.end();
  501. return;
  502. }
  503. let filePath;
  504. // 如果是 admin 相关的请求,从 admin 目录提供
  505. if (pathname.startsWith('/admin/')) {
  506. // 移除开头的 /,然后拼接路径
  507. const relativePath = pathname.substring(1); // 移除开头的 /
  508. // 解码 URL 编码的路径(处理中文、空格等特殊字符)
  509. const decodedPath = decodeURIComponent(relativePath);
  510. filePath = path.join(ADMIN_DIR, decodedPath.replace(/^admin\//, ''));
  511. } else if (pathname.startsWith('/texture/') || pathname.startsWith('/avatar/') || pathname.startsWith('/users/')) {
  512. // 如果是 texture、avatar 或 users 相关的请求,从 server 目录提供
  513. // 移除开头的 /,然后拼接路径
  514. const relativePath = pathname.substring(1); // 移除开头的 /
  515. // 解码 URL 编码的路径(处理中文、空格等特殊字符)
  516. const decodedPath = decodeURIComponent(relativePath);
  517. filePath = path.join(SERVER_DIR, decodedPath);
  518. } else {
  519. // 其他请求从 Client 目录提供
  520. const relativePath = pathname.startsWith('/') ? pathname.substring(1) : pathname;
  521. // 解码 URL 编码的路径
  522. const decodedPath = decodeURIComponent(relativePath);
  523. filePath = path.join(CLIENT_DIR, decodedPath);
  524. }
  525. // 检查文件是否存在并获取文件信息
  526. fs.stat(filePath, (statErr, stats) => {
  527. if (statErr) {
  528. // 文件不存在,返回 404(静默处理)
  529. res.writeHead(404, { 'Content-Type': 'text/plain' });
  530. res.end('');
  531. return;
  532. }
  533. // 获取文件扩展名
  534. const ext = path.extname(filePath).toLowerCase();
  535. const contentType = mimeTypes[ext] || 'application/octet-stream';
  536. // 构建响应头
  537. const headers = {
  538. 'Content-Type': contentType
  539. };
  540. // 如果是图片文件,添加缓存头
  541. if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif') {
  542. // 设置长期缓存(1年)
  543. headers['Cache-Control'] = 'public, max-age=31536000, immutable';
  544. // 添加 ETag 用于缓存验证
  545. const etag = `"${stats.mtime.getTime()}-${stats.size}"`;
  546. headers['ETag'] = etag;
  547. // 检查客户端是否发送了 If-None-Match 头(缓存验证)
  548. const ifNoneMatch = req.headers['if-none-match'];
  549. if (ifNoneMatch === etag) {
  550. // 文件未修改,返回 304 Not Modified
  551. res.writeHead(304, headers);
  552. res.end();
  553. return;
  554. }
  555. }
  556. // 读取文件
  557. fs.readFile(filePath, (readErr, data) => {
  558. if (readErr) {
  559. res.writeHead(500, { 'Content-Type': 'text/plain' });
  560. res.end('Internal Server Error');
  561. return;
  562. }
  563. // 返回文件
  564. res.writeHead(200, headers);
  565. res.end(data);
  566. });
  567. });
  568. });
  569. // 启动服务器
  570. server.listen(PORT, () => {
  571. // 立即清屏(使用 ANSI 转义序列)
  572. process.stdout.write('\x1B[2J\x1B[0f');
  573. // 使用 setTimeout 延迟输出,确保批处理脚本的输出先完成
  574. setTimeout(() => {
  575. console.log('========================================');
  576. console.log(' PNG 序列动画预览工具 - 服务器');
  577. console.log('========================================');
  578. console.log(`服务器运行在: http://localhost:${PORT}`);
  579. console.log(`用户数据路径: ${path.join(SERVER_DIR, 'users')}`);
  580. console.log('========================================');
  581. console.log('按 Ctrl+C 或关闭此窗口停止服务器');
  582. console.log('');
  583. }, 1000); // 延迟 1000ms 输出,避免与批处理脚本输出重叠
  584. });
  585. // 优雅关闭处理
  586. function gracefulShutdown() {
  587. console.log('\n正在关闭服务器...');
  588. server.close(() => {
  589. console.log('服务器已关闭');
  590. process.exit(0);
  591. });
  592. }
  593. process.on('SIGINT', gracefulShutdown);
  594. process.on('SIGTERM', gracefulShutdown);
  595. // Windows 下处理窗口关闭事件
  596. if (process.platform === 'win32') {
  597. const readline = require('readline');
  598. const rl = readline.createInterface({
  599. input: process.stdin,
  600. output: process.stdout
  601. });
  602. rl.on('SIGINT', () => {
  603. process.emit('SIGINT');
  604. });
  605. }