导航

Node.Js fs模块---文件监听

Posted on 2017-12-22 10:28  枫随风落  阅读(987)  评论(0)    收藏  举报
const fs = require("fs");
const path = require("path");


let watcherObj = path.join(__dirname,'../files/innerDir/innerTxt.txt');

//eventType 可以是 'rename' 或 'change'
//当改名或出现或消失的时候触发rename
//recursive:是否监听到内层子目录,默认false;
try {

    let myWatcher = fs.watch(watcherObj,{encoding:'utf8',recursive:true},(event,filename) => {
        if(event == 'change'){
            console.log("哥,处罚了change事件!")
        }
        
        console.log(event)
        //encoding:文件名编码格式,buffer、默认:utf8等;
        //filename有可能为空
        if(filename){
            console.log('filename:::',filename)
        }
        
    })

    //change 事件会触发多次  
    myWatcher.on('change',function(err,filename){  
        console.log(filename+'-发生变化');  
    }); 

    //50秒后 关闭监视  
    setTimeout(function(){  
        myWatcher.close()
    },5000);
    
} catch (error) {
    console.log('文件不存在!!!')
}

 

文件监视,此效率要低于上边的watch,首选watch

const fs = require("fs");
const path = require("path");

let watcherobj = path.resolve("../files/innerDir/innerTxt4.txt");
let thePrev = null;

let listenerFunc = (curr,prev)=>{
    
    if ((Date.parse(curr.ctime) > 0) && (JSON.stringify(prev) == thePrev)) {  
        console.log('文件被创建!!'); 
        
    } else if (Date.parse(curr.ctime) == 0) {  
        console.log('文件不存在!!');  
        //删除时候记录,以便恢复时做对比
        thePrev = JSON.stringify(prev);
    }else if(Date.parse(curr.mtime) != Date.parse(prev.mtime)) {  
        console.log('文件有修改');  
    }else{
        console.log('文件wu修改');  
    }
 
}

fs.watchFile(watcherobj,{interval: 1000},listenerFunc)

setTimeout(function(){
    fs.unwatchFile(watcherobj,listenerFunc)
},10000)