91 lines
2.2 KiB
JavaScript
91 lines
2.2 KiB
JavaScript
'use strict';
|
|
|
|
const dotenv = require('dotenv');
|
|
const schedule = require('node-schedule');
|
|
const path = require('path');
|
|
const os = require('os');
|
|
|
|
/**
|
|
* 环境变量
|
|
*/
|
|
process.env = {}; // 清除系统自带的环境变量
|
|
dotenv.config('./.env'); // 导入 .env 文件中的环境变量
|
|
// console.log(process.env);
|
|
|
|
const DEBUG_MODE = process.env.DEBUG_MODE == true;
|
|
const EXECUTE_AT_STARTUP = process.env.EXECUTE_AT_STARTUP == true;
|
|
|
|
const ROOT_PATH = path.join(__dirname, process.env.DATA_FOLDER ?? 'data');
|
|
|
|
|
|
/**
|
|
* 调试模式
|
|
*/
|
|
if (DEBUG_MODE) {
|
|
console.log('DEBUG_MODE is on');
|
|
console.log('Environment variables: ', process.env);
|
|
}
|
|
|
|
/**
|
|
* 引入模块
|
|
*/
|
|
const get_hotband = require('./src/get_hotband');
|
|
const execute_command = require('./src/execute_command');
|
|
|
|
|
|
/**
|
|
* 开始运行
|
|
*/
|
|
console.log("Start running ...");
|
|
|
|
|
|
/**
|
|
* 程序主函数
|
|
*/
|
|
async function start() {
|
|
// 爬取热搜数据
|
|
await get_hotband.main();
|
|
}
|
|
|
|
// 调试模式下,程序一启动就首先运行一次
|
|
if (EXECUTE_AT_STARTUP) {
|
|
process.stdout.write("程序启动时,立即运行一次\t");
|
|
start();
|
|
}
|
|
|
|
// 每分钟的第 5 秒执行一次
|
|
// 这里指定第 5 秒是为了稍微与微博服务器热榜更新时间错开,避免因为微秒级误差造成拉取两次相同的热榜数据
|
|
// refer: https://www.npmjs.com/package/node-schedule
|
|
const scheduleJob = schedule.scheduleJob('05 * * * * *', start);
|
|
|
|
|
|
/**
|
|
* 定时将热搜数据推送到 Git 仓库
|
|
*/
|
|
async function pushToGitRepo() {
|
|
let commands = [
|
|
'git status',
|
|
'git pull',
|
|
'git add .',
|
|
`git commit -m "${new Date(Date.now() + 8 * 3600 * 1000).toISOString().substring(0, 19).replace('T', ' ')} update"`,
|
|
`git push origin master`,
|
|
'git status',
|
|
];
|
|
switch (os.type()) {
|
|
case 'Windows_NT': // Windows
|
|
commands.unshift('dir');
|
|
break;
|
|
|
|
case 'Darwin': // Mac OS X
|
|
case 'Linux': // Linux
|
|
default:
|
|
commands.unshift('pwd');
|
|
break;
|
|
}
|
|
let outputs = await execute_command.execute(ROOT_PATH, commands);
|
|
console.log(commands, outputs);
|
|
}
|
|
|
|
// 每个小时同步一次
|
|
schedule.scheduleJob('0 0 * * * *', pushToGitRepo);
|