UNPKG

filewriter-siawwad

Version:

Users can import this module into their Node.js scripts and utilize the functions to create new log every hour, ensuring organized and time-stamping logs.

80 lines (70 loc) 2.58 kB
const fs = require('fs').promises; const fss = require('fs'); const path = require('path'); let logDir = path.join(__dirname,'Logs'); let currentLogFile; let lastLogFileCreationTime; let firstTime; let secondTime; let duration; const month = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"]; const createNewLogFile = async () => { const timestamp = new Date();//.toISOString().replace(/[-:]/g,'').slice(0,-8); // const counter=Math.floor(Date.now()/1000); const filename = `Log-${timestamp.getFullYear()}-${month[timestamp.getMonth()]}-${timestamp.getDate()} -T ${timestamp.getHours()}.log`; // const filename = Log-${timestamp}-${counter}.log; const filePath = path.join(logDir, filename); if (fss.existsSync(filePath)) { lastLogFileCreationTime = timestamp.getHours(); return filePath; } await fs.writeFile(filePath, ''); lastLogFileCreationTime = timestamp.getHours(); return filePath; }; const setLogDir = (dir) => { logDir = path.resolve(dir); }; const shouldCreateNewLogFile = () => { const now = new Date; // const oneHour=1000*60; // return !currentLogFile || now-lastLogFileCreationTime>=oneHour; return !currentLogFile || now.getHours() != lastLogFileCreationTime; }; const writeToFile = async (filePath, data) => { await fs.appendFile(filePath, data + '\n'); }; const processDataAsync = async (data) => { if (!currentLogFile || shouldCreateNewLogFile()) { currentLogFile = await createNewLogFile(); } await writeToFile(currentLogFile, data); }; const logData = async (data, type = 'log') => { // await processDataAsync(data); let tempData = data; let finalData; if (type === 'log') { const timestamp = new Date(); const currentDate = `${timestamp.getHours()}:${timestamp.getMinutes()}:${timestamp.getSeconds()}`; finalData = `${currentDate}\t${tempData}`; } else finalData = tempData; await processDataAsync(String(finalData)); }; const stratTimer = () => { firstTime = Date.now() / 1000; }; const endTimer = async (data) => { secondTime = Date.now() / 1000; duration = secondTime - firstTime; // timeInfo = StartTime is: ${firstTime} , EndTime is ${secondTime}, the Duration is:${duration}; // await logData(timeInfo); await logData(`${data}: ${duration} ms.`, 'timer'); }; module.exports = { setLogDir, logData, stratTimer, endTimer, };