const fs = require('fs');
const path = require('path');
const directoryPath = process.cwd();
const logFilePath = path.join(directoryPath, 'fileChanges.log');
// Function to log messages to the log file
const logToFile = (message) => {
const timestamp = new Date().toISOString();
const logMessage = `[${timestamp}] ${message}\n`;
fs.appendFile(logFilePath, logMessage, (err) => {
if (err) {
console.error('Failed to write to log file', err);
}
});
};
// Function to monitor a single file for modifications
const watchFile = (filePath) => {
// Skip tracking changes to 'fileChanges.log'
if (filePath === logFilePath) {
return;
}
fs.watchFile(filePath, (curr, prev) => {
if (curr.mtime !== prev.mtime) {
logToFile(`File modified: ${filePath}`);
console.log(`File modified: ${filePath}`);
}
});
};
// Function to start watching all files in the directory
const watchAllFiles = () => {
fs.readdir(directoryPath, (err, files) => {
if (err) {
console.error(`Could not read directory: ${err}`);
return;
}
// Watch each file in the directory, excluding 'fileChanges.log'
files.forEach((file) => {
const filePath = path.join(directoryPath, file);
if (file !== 'fileChanges.log') {
fs.stat(filePath, (err, stats) => {
if (err) {
console.error(`Could not stat file: ${err}`);
} else if (stats.isFile()) {
watchFile(filePath);
console.log(`Now watching file: ${filePath}`);
}
});
}
});
});
};
// Watch the directory itself for new files
fs.watch(directoryPath, (eventType, filename) => {
if (filename && eventType === 'rename') {
const filePath = path.join(directoryPath, filename);
// Check if it's a new file and start watching it
if (fs.existsSync(filePath) && filename !== 'fileChanges.log') {
fs.stat(filePath, (err, stats) => {
if (err) {
console.error(`Could not stat file: ${err}`);
} else if (stats.isFile()) {
watchFile(filePath);
console.log(`New file detected and now watching: ${filePath}`);
}
});
}
}
});
// Start watching all existing files initially
watchAllFiles();
console.log(`Monitoring directory: ${directoryPath}`);