You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.5 KiB

const express = require('express');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
const history = require('connect-history-api-fallback');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(bodyParser.json());
// GET: 根据 level 读取文件内容
app.get('/api/getData', (req, res) => {
const { level } = req.query;
if (!level) {
return res.status(400).json({ error: '缺少 level 参数' });
}
try {
const absPath = path.resolve(level);
if (!fs.existsSync(absPath)) {
return res.status(404).json({ error: `文件不存在: ${absPath}` });
}
const content = fs.readFileSync(absPath, 'utf-8');
res.json({ path: absPath, content });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// POST: 根据 level 写入文件内容
app.post('/api/putData', (req, res) => {
const { level, content } = req.body;
if (!level || content === undefined) {
return res.status(400).json({ error: '缺少 level 或 content 参数' });
}
try {
const absPath = path.resolve(level);
fs.writeFileSync(absPath, content, 'utf-8');
res.json({ message: '文件已更新', path: absPath });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// 静态目录为当前运行目录
app.use(history());
app.use(express.static(process.cwd()));
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});