Skip to content

Instantly share code, notes, and snippets.

@StevenMcD
Created October 21, 2012 19:15
Show Gist options
  • Save StevenMcD/3928150 to your computer and use it in GitHub Desktop.
Save StevenMcD/3928150 to your computer and use it in GitHub Desktop.
NodeJS directory watcher - basic monitor&move script
function Watcher(watchDir, processedDir){
this.watchDir = watchDir;
this.processedDir = processedDir;
};
var events = require('events');
Watcher.prototype = new events.EventEmitter();
var fs = require('fs'),
watchDir = './watch',
processedDir = './done';
Watcher.prototype.watch = function(){
var watcher = this;
fs.readdir(this.watchDir, function(err, files){
if(err) throw err;
for(index in files){
watcher.emit('process', files[index]);
}
});
};
Watcher.prototype.start = function(){
var watcher = this;
fs.watchFile(watchDir, function(){
watcher.watch();
});
};
var watcher = new Watcher("<directoryToWatch>", "<directoryToCopyTo>");
watcher.on('process', function(file){
var watchFile = this.watchDir + "/" + file;
var processedFile = this.processedDir + "/" + file.toLowerCase();
fs.rename(watchFile, processedFile, function(err){
if(err) throw err;
});
});
watcher.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment