北斗应用技术培训报名系统
This commit is contained in:
72
app/middleware/log.js
Normal file
72
app/middleware/log.js
Normal file
@@ -0,0 +1,72 @@
|
||||
// 错误日志
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const dirCheck = (dirPath) => {
|
||||
// 检查文件夹是否存在
|
||||
fs.access(dirPath, fs.constants.F_OK, (err) => {
|
||||
if (err) {
|
||||
// 文件夹不存在
|
||||
console.log('文件夹不存在,正在创建...');
|
||||
fs.mkdir(dirPath, { recursive: true }, (err) => {
|
||||
if (err) throw err;
|
||||
console.log('文件夹已创建');
|
||||
});
|
||||
} else {
|
||||
// 文件夹存在
|
||||
console.log('文件夹已存在');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = (filePath, msg) => {
|
||||
// 获取时间
|
||||
let now = new Date(),
|
||||
times = {
|
||||
year: now.getFullYear(),
|
||||
month: now.getMonth() + 1,
|
||||
day: now.getDate(),
|
||||
hour: now.getHours(),
|
||||
minute: now.getMinutes(),
|
||||
second: now.getSeconds()
|
||||
};
|
||||
// 获取操作系统类型
|
||||
const type = os.type();
|
||||
console.log(`操作系统类型: ${type}`);
|
||||
filePath = path.join(__dirname, filePath);
|
||||
dirCheck(filePath);
|
||||
const yearPath = filePath + '/' + times.year;
|
||||
dirCheck(yearPath);
|
||||
const monthPath = yearPath + '/' + times.month;
|
||||
dirCheck(monthPath);
|
||||
const dayPath = monthPath + '/' + times.day + '.txt';
|
||||
const logTime = '[' + times.year + '-' + times.month + '-' + times.day + '>>>' + times.hour + ':' + times.minute + ':' + times.second + ']' + '>>>';
|
||||
let crlf;
|
||||
// 判断操作系统类型,设置换行符
|
||||
if (type === 'Windows_NT') {
|
||||
crlf = '\n';
|
||||
} else {
|
||||
crlf = '\r\n';
|
||||
}
|
||||
// 读取文件内容
|
||||
fs.readFile(dayPath, 'utf8', (err, data) => {
|
||||
if (err) {
|
||||
if (err.code === 'ENOENT') {
|
||||
// 文件不存在,直接写入新内容(这里实际上还是使用了覆盖的方式)
|
||||
fs.writeFile(dayPath, logTime + msg + crlf, (err) => {
|
||||
if (err) throw err;
|
||||
console.log('文件已创建并写入新内容');
|
||||
});
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
} else {
|
||||
// 文件存在,追加新内容
|
||||
fs.appendFile(dayPath, logTime + msg + crlf, (err) => {
|
||||
if (err) throw err;
|
||||
console.log('新内容已追加到文件');
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user