Skip to content

Instantly share code, notes, and snippets.

@gsampaio
Created December 7, 2011 02:12
Show Gist options
  • Save gsampaio/1441116 to your computer and use it in GitHub Desktop.
Save gsampaio/1441116 to your computer and use it in GitHub Desktop.
Node Daemon to watch file change and send to email
/*
Node filewatch to email module by Guilherme Martinez Sampaio
require npm, daemon and mail
Make sure to change the configuration object
To install:
npm: curl http://npmjs.org/install.sh | sh
daemon: npm install daemon
mail: npm install mail
*/
var configuration = {
file:'/tmp/test',
smtp_config: {
host: 'smtp.gmail.com',
username: 'someone@gmail.com',
password: '**password**'
},
mail_properties: {
from: 'someone@somewhere.com',
to: ['somebody@somewhere.com'],
subject: 'Email Subject'
},
daemon: {
log_file: '/tmp/stdmail.log',
pid_file: '/tmp/stdmail.pid'
},
timeout: 1000,
};
var daemon = require('daemon');
var fs = require('fs');
var email = require('mail').Mail({
host: configuration.smtp_config.host,
username: configuration.smtp_config.username,
password: configuration.smtp_config.password
});
var currentDate = new Date();
var file = configuration.file;
function execute() {
setTimeout(checkFile, configuration.timeout);
}
function checkFile() {
fs.stat(file, function(err, stats){
if (stats.mtime.getTime() > currentDate.getTime()) {
currentDate = stats.mtime;
sendEmail();
}
});
execute();
}
function sendEmail () {
var data = fs.readFileSync(file, 'ascii');
email.message({
from: configuration.mail_properties.from,
to: configuration.mail_properties.to,
subject: configuration.mail_properties.subject
}).body(data).send(function(err) {});
console.log(data);
}
console.log("Starting File Watcher Daemon");
execute();
fs.open(configuration.daemon.log_file, 'w+', function (err, fd) {
daemon.start(fd);
daemon.lock(configuration.daemon.pid_file);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment