import fs from "fs"; import chokidar from "chokidar"; import moment from "moment"; import LogDetectFile from "App/Models/LogDetectFile"; import LogReport from "App/Models/LogReport"; // export default class loggerAPI { export function runtimeCheckLogs(folderPath) { console.log(folderPath) try { let fileList = []; let fileList_old = []; // Function to update the list of files async function updateFileList() { let dateNow = moment(Date.now()).format("YYYY/MM/DD"); fileList = fs.readdirSync(folderPath); // console.log("File list updated:", fileList); fileList.map((file) => { const filePath = `${folderPath}/${file}`; const stats = fs.statSync(filePath); //scan file today if (dateNow !== moment(stats.mtime).format("YYYY/MM/DD")) { fileList = fileList.filter((i) => i !== file); } }); } // Watch the folder for new files const folderWatcher = chokidar.watch(folderPath); // folderWatcher.setMaxListeners(20); folderWatcher.on("add", async (filePath) => { console.log(`New file added: ${filePath}`); //import log new file await LogDetectFile.firstOrCreate({file_name:filePath.split("\\")[filePath.split("\\").length -1]},{file_name:filePath.split("\\")[filePath.split("\\").length -1]}) // updateFile; fileList_old = fileList; updateFileList(); watchFilesInList(); }); // Watch for changes in the files listed function watchFilesInList() { // console.log("--------->", fileList); //get date now //check new file fileList ?.filter((i) => fileList_old.includes(i) === false) ?.forEach((fileName) => { //path file const filePath = `${folderPath}/${fileName}`; //get date modified // const stats = fs.statSync(filePath); // //scan file today // if (dateNow === moment(stats.mtime).format("2023/08/20")) { const scan = fs.watchFile( filePath, { interval: 10000 }, async (eventType) => { //check special item, extra RAM, error in log //true: import log to log_report table, send report to Zulip const log = await LogDetectFile.findBy('file_name', fileName) await LogReport.create({ detected_content: 'virk', line: 123, id_file: log?.id_ldf }) //false: next console.log(`${fileName} has changed (${eventType})`); } ); //setMaxListeners scan.setMaxListeners(0); // } }); } } catch (error) { console.log(error); } }