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.
65 lines
1.6 KiB
65 lines
1.6 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());
|
|
|
|
// 读取文件内容
|
|
app.get('/api/getData', (req, res) => {
|
|
const filePath = process.env.CURRENT_LEVEL_PATH;
|
|
if (!filePath) {
|
|
return res.status(400).json({ error: '环境变量 CURRENT_LEVEL_PATH 未设置' });
|
|
}
|
|
|
|
try {
|
|
const absPath = path.resolve(filePath);
|
|
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 });
|
|
}
|
|
});
|
|
|
|
// 更新文件内容
|
|
app.post('/api/putData', (req, res) => {
|
|
const filePath = process.env.CURRENT_LEVEL_PATH;
|
|
if (!filePath) {
|
|
return res.status(400).json({ error: '环境变量 CURRENT_LEVEL_PATH 未设置' });
|
|
}
|
|
|
|
let { content } = req.body;
|
|
if (content === undefined) {
|
|
return res.status(400).json({ error: '缺少 content 参数' });
|
|
}
|
|
|
|
try {
|
|
const absPath = path.resolve(filePath);
|
|
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}`);
|
|
});
|