files-monitor
Version:
Monitor files and inform if they changed
89 lines (80 loc) • 2.44 kB
JavaScript
// TODO: Add param to generate empty ".filesmonitorrc".
// TODO: Refactor all this code later.
// Import.
const fs = require('fs');
const os = require('os');
const path = require('path');
const childProcess = require('child_process');
const md5File = require('md5-file');
const Sendmail = require('sendmail');
// Constants.
const HOME_DIR = os.homedir();
const USER_CONFIG_FILE = os.platform() === 'win32' ? 'filesmonitorrc' : '.filesmonitorrc';
const USER_CONFIG_PATH = path.join(HOME_DIR, USER_CONFIG_FILE);
const ENCODING = 'utf8';
// Init.
const sendmail = Sendmail({ silent: true });
// Inform.
console.log(`Files Monitor started with PID ${process.pid}.`);
// Define config.
let email;
let command;
let checkInterval;
let filesInfo = [];
try {
const configContent = fs.readFileSync(USER_CONFIG_PATH, {
encoding: ENCODING
});
const config = JSON.parse(configContent);
filesInfo = config.files.map(v => ({ path: v, hash: null }));
email = config.email;
command = config.command;
checkInterval = config.checkInterval;
console.log(`Files to check: ${config.files.map(v => `"${v}"`).join(', ')}.`);
} catch (err) {
console.log(`Can't define config in file "${USER_CONFIG_PATH}".`);
process.exit(1);
}
// Check files.
setInterval(() => {
for (let i = 0; i < filesInfo.length; i++) {
const fileInfo = filesInfo[i];
const previousHash = fileInfo.hash;
let calculatedHash;
try {
calculatedHash = md5File.sync(fileInfo.path);
} catch (err) {
console.error(err);
}
const now = new Date();
if (previousHash && calculatedHash !== previousHash) {
// Inform.
const message = `File "${fileInfo.path}" at "${os.hostname()}" changed accordance to check at ${now.toISOString()}.`;
console.log(message);
if (email) {
try {
sendmail({
from: 'Files Monitor <noreply@example.com>',
to: email,
subject: 'Files Monitor alert',
html: message
});
} catch (err) {
console.error(err);
}
}
// Run command.
if (command) {
console.log(`Command "${command}" started.`);
childProcess.exec(command, (err, stdout) => {
if (err) {
console.error(err);
}
console.log(stdout);
});
}
}
fileInfo.hash = calculatedHash;
}
}, checkInterval * 1000);