Created
April 9, 2014 19:22
-
-
Save ericksond/10305281 to your computer and use it in GitHub Desktop.
node.js filewatcher that sends signal to a remote api when triggered
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * | |
| * 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