|
const express = require('express'); |
|
const { exec } = require('child_process'); |
|
const fs = require('fs'); |
|
const path = require('path'); |
|
const app = express(); |
|
const port = process.env.PORT || 8080; |
|
|
|
|
|
const logDir = path.join(process.env.HOME, 'logs'); |
|
if (!fs.existsSync(logDir)) { |
|
fs.mkdirSync(logDir, { recursive: true }); |
|
} |
|
|
|
function log(message) { |
|
const timestamp = new Date().toISOString(); |
|
const logMessage = `${timestamp}: ${message}\n`; |
|
console.log(logMessage); |
|
fs.appendFileSync(path.join(logDir, 'app.log'), logMessage); |
|
} |
|
|
|
app.get('/', (req, res) => { |
|
res.send(` |
|
<h1>登录脚本状态</h1> |
|
<p>上次执行时间:${lastRunTime || '尚未执行'}</p> |
|
<p>下次执行时间:${nextRunTime || '未设置'}</p> |
|
<a href="/run">立即执行脚本</a> |
|
<br><br> |
|
<a href="/logs">查看日志</a> |
|
`); |
|
}); |
|
|
|
app.get('/logs', (req, res) => { |
|
const logPath = path.join(logDir, 'app.log'); |
|
fs.readFile(logPath, 'utf8', (err, data) => { |
|
if (err) { |
|
res.status(500).send('无法读取日志文件'); |
|
return; |
|
} |
|
res.send(`<pre>${data}</pre>`); |
|
}); |
|
}); |
|
|
|
let lastRunTime = null; |
|
let nextRunTime = null; |
|
|
|
function runLoginScript() { |
|
log('开始执行登录脚本'); |
|
exec('node login.js', (error, stdout, stderr) => { |
|
if (error) { |
|
log(`执行错误: ${error.message}`); |
|
return; |
|
} |
|
if (stderr) { |
|
log(`脚本错误输出: ${stderr}`); |
|
return; |
|
} |
|
log(`脚本输出:\n${stdout}`); |
|
}); |
|
lastRunTime = new Date().toISOString(); |
|
nextRunTime = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(); |
|
} |
|
|
|
app.get('/run', (req, res) => { |
|
runLoginScript(); |
|
res.send('脚本执行已启动,请查看日志获取详细信息。'); |
|
}); |
|
|
|
|
|
setInterval(runLoginScript, 7 * 24 * 60 * 60 * 1000); |
|
|
|
app.listen(port, () => { |
|
log(`服务器运行在 http://localhost:${port}`); |
|
runLoginScript(); |
|
}); |