fix: 完善resetState重置与端口配置
This commit is contained in:
+31
-21
@@ -2,7 +2,7 @@ const http = require('http');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const PORT = process.env.PORT || 3001;
|
||||
const PORT = process.env.PORT || 3008;
|
||||
const DATA_DIR = path.join(__dirname, '../data');
|
||||
const DATA_FILE = path.join(DATA_DIR, 'quiz_stats.json');
|
||||
const QUESTIONS_FILE = path.join(__dirname, '../questions.json');
|
||||
@@ -19,6 +19,33 @@ let state = {
|
||||
totalAnswered: 0
|
||||
};
|
||||
|
||||
// 获取所有题目的默认权重
|
||||
function getDefaultWeights() {
|
||||
let defaultWeights = {};
|
||||
if (fs.existsSync(QUESTIONS_FILE)) {
|
||||
try {
|
||||
const qData = JSON.parse(fs.readFileSync(QUESTIONS_FILE, 'utf-8'));
|
||||
qData.forEach(q => {
|
||||
defaultWeights[q.id] = 1;
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('[Init] 读取 questions.json 失败:', e);
|
||||
}
|
||||
}
|
||||
return defaultWeights;
|
||||
}
|
||||
|
||||
// 重置状态
|
||||
function resetState() {
|
||||
state = {
|
||||
weights: getDefaultWeights(),
|
||||
history: [],
|
||||
totalAnswered: 0
|
||||
};
|
||||
saveState();
|
||||
console.log('[Reset] 全局刷题数据已重置。');
|
||||
}
|
||||
|
||||
// 初始化状态
|
||||
function initState() {
|
||||
if (fs.existsSync(DATA_FILE)) {
|
||||
@@ -32,27 +59,10 @@ function initState() {
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化默认权重
|
||||
let defaultWeights = {};
|
||||
if (fs.existsSync(QUESTIONS_FILE)) {
|
||||
try {
|
||||
const qData = JSON.parse(fs.readFileSync(QUESTIONS_FILE, 'utf-8'));
|
||||
qData.forEach(q => {
|
||||
defaultWeights[q.id] = 1;
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('[Init] 读取 questions.json 失败:', e);
|
||||
}
|
||||
}
|
||||
|
||||
state = {
|
||||
weights: defaultWeights,
|
||||
history: [],
|
||||
totalAnswered: 0
|
||||
};
|
||||
saveState();
|
||||
resetState();
|
||||
}
|
||||
|
||||
|
||||
// 异步持久化保存
|
||||
function saveState() {
|
||||
const tmpFile = `${DATA_FILE}.tmp`;
|
||||
@@ -146,7 +156,7 @@ const server = http.createServer((req, res) => {
|
||||
}
|
||||
|
||||
if (req.method === 'POST' && (pathname === '/reset' || pathname === '/reset/')) {
|
||||
initState();
|
||||
resetState();
|
||||
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
||||
res.end(JSON.stringify({ success: true, message: 'Stats reset' }));
|
||||
return;
|
||||
|
||||
Reference in New Issue
Block a user