Skip to content

Instantly share code, notes, and snippets.

@ericksond
Created April 9, 2014 19:22
Show Gist options
  • Select an option

  • Save ericksond/10305281 to your computer and use it in GitHub Desktop.

Select an option

Save ericksond/10305281 to your computer and use it in GitHub Desktop.
node.js filewatcher that sends signal to a remote api when triggered
/*
*
* filewatcher.js
* This file watcher application is written in node.js
* by Erickson Delgado.
*
*/
var fs = require('fs')
, request = require('request')
, async = require('async')
, log = require('book').default() // panic, error, warn, info, debug, trace
, id
, config;
try {
config = JSON.parse(fs.readFileSync('d:\\filewatcher\\config.json'));
} catch (e) {
log.error('JSON parsing error: ' + e);
}
var watch = function ( dir ) {
try {
fs.watch( dir.path, function( event, file ) {
logfile = config.log_dir + '/filewatcher' + require('strftime')("-%Y%m%d") + '.log'
log.use( require('book-file')({
filename: logfile
}));
if ( event === 'change' ) {
log.trace( require('strftime')("%Y-%m-%d %H:%M:%S") + ' ' + event.toUpperCase() + ', file: ' + file );
if ( id ) {
log.trace('id: ' + id);
clearTimeout( id );
id = null;
}
id = setTimeout( function() {
var ts = new Date();
log.info( require('strftime')("%Y-%m-%d %H:%M:%S") + ' file change detected. Attempting POST to ' + config.api + ' for job_id ' + dir.job_id);
var options = {
uri: config.api,
method: 'POST',
json: {
"job_id": dir.job_id
}
}
request(options, function(error, response, body) {
if (!error && response.statusCode == 200) {
log.info(JSON.stringify(body));
} else {
log.error('Error in POST request: ' + error);
}
});
}, 15000 ); // 15s wait to avoid duplicates
}
});
} catch (e) {
log.error(e);
}
}
async.map(config.dirs, watch, function(err, results){
log.trace('async results: ' + results);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment