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; // 使用 HOME 环境变量来创建日志目录 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(`

登录脚本状态

上次执行时间:${lastRunTime || '尚未执行'}

下次执行时间:${nextRunTime || '未设置'}

立即执行脚本

查看日志 `); }); 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(`
${data}
`); }); }); 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('脚本执行已启动,请查看日志获取详细信息。'); }); // 每7天自动运行一次脚本 setInterval(runLoginScript, 7 * 24 * 60 * 60 * 1000); app.listen(port, () => { log(`服务器运行在 http://localhost:${port}`); runLoginScript(); // 启动时立即运行一次 });