fs.watchFile(filename,[optitions],listener)来监测文件是否发生改变
optations:{persistent:true,inteval:6000},persistent为true时候,表示文件监控不会退出应用程序。interval:表示多长时间监控一次。
var fs=require("fs");
fs.watchFile('./watch.txt',function(curr,prev){
if(Date.parse(prev.ctime)==0){
console.log("文件被创建");
}else if(Date.parse(curr.ctime)==0){
console.log("文件被删除");
}else if(Date.parse(curr.mtime)!=Date.parse(prev.mtime)){
console.log("文件被修改");
}
})
挡在当前目录创建、修改删除这个文件时候,控制台输出如下
取消监控
fs.unwatchFile(filename,[lisntner])
var fs=require("fs");
var fun1=function(curr,prev){
if(Date.parse(prev.ctime)==0){
console.log("文件被创建");
}else if(Date.parse(curr.ctime)==0){
console.log("文件被删除");
}else if(Date.parse(curr.mtime)!=Date.parse(prev.mtime)){
console.log("文件被修改");
}
};
var fun2=function(curr,prev){
if(Date.parse(curr.ctime)!=0){
console.log("sfsdfsdfsdfd");
}
}
fs.watchFile('./watch.txt',fun1);
fs.watchFile('./watch.txt',fun2);
fs.unwatchFile('./watch.txt',fun1);
对目录或文件进行监控
watch(filename,[optitons],[listener])
注意:用watch方法filename必须存在
filename:要对监测的目录或者文件名字
optations:{persistent:true},监测不退出程序
回调:function(event,filename)
event:rename(文件被从命名移动)时候触发
change(文件被更改时候)
filename:更改的文件名
watch(filename)返回一个fs.watcher对象
该对象有close方法,关闭j监测
var fs=require("fs");
var watcher=fs.watch("./wather.txt");
watcher.on('change',function(event,filename){
console.log(event);
console.log(filename);
watcher.close();
})