Node.js, watching for file create/delete
Watching for file create and delete used to be simple in node.js 0.6, all you had to do is use the fs.watchFile.
Now if you want to do that in node 0.8, let's say that all you have is a file path and you want to be notified each time it is created or removed.
function watchFile(filepath, oncreate, ondelete) {
var
fs = require('fs'),
path = require('path'),
filedir = path.dirname(filepath),
filename = path.basename(filepath);
fs.watch(filedir, function(event, who) {
if (event === 'rename' && who === filename) {
if (fs.existsSync(filepath)) {
oncreate();
} else {
ondelete();
}
}
}
}Written by Vincent Voyer
Related protips
1 Response
Thanks, this is very useful !
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Nodejs
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#