登录
注册
node.js 学习社区
node.js watch 模块监听文件夹变化

新手村长老

2015-03-03 11:24

fs.watch

其中Node.JS的文件系统也可侦听某个目录的改变, 如 fs.watch
        fs.watch('somedir', function (event, filename) {
         console.log('event is: ' + event);
         if (filename) {
           console.log('filename provided: ' + filename);
         } else {
           console.log('filename not provided');
         } 
        });
    

其中fs.watch的最大缺点就是不支持子文件夹的侦听,并且在很多情况下会侦听到两次事件(很多编辑器在保存的时侯是先把原文件清空,再进行保存,因此会触发两次文件夹改变事件)。因此需要一些开源的模块来监听文件夹目录的改变。

chokidar

chokidar   是一个基于node.JS的监听文件夹改变模块。

安装
        npm install chokidar
    

示例
        var chokidar = require('chokidar'); 
        var watcher = chokidar.watch('file, dir, or glob', {
         ignored: /[\/\\]\./, persistent: true 
        }); 
        var log = console.log.bind(console); 
        watcher.on('add', function(path) { log('File', path, 'has been added');
        }).on('addDir', function(path) { log('Directory', path, 'has been
        added'); }) .on('change', function(path) { log('File', path, 'has been changed');
        }) .on('unlink', function(path) { log('File', path, 'has been removed');
        }) .on('unlinkDir', function(path) { log('Directory', path, 'has been
        removed'); }) .on('error', function(error) { log('Error happened', error); })
         .on('ready', function() { log('Initial scan complete. Ready for
        changes.'); }).on('raw', function(event, path, details) { log('Raw event info:',
        event, path, details); })
    

watch

Watch 是另一个监听文件夹改变的Node.JS模块

安装
        npm install watch
    

示例,侦听所有改变事件
        watch.watchTree('/home/mikeal', function (f, curr, prev) {
           if (typeof f == "object" && prev === null &&curr === null) {
              // Finished walking the tree
           } else if (prev === null) {
             // f is a new file
            } else if (curr.nlink === 0) {
              // f was removed
            } else {
              // f was changed
            } 
        })
    

示例,侦听不同事件
 
        var watch = require('watch') 
        watch.createMonitor('/home/mikeal', function (monitor) {
            monitor.files['/home/mikeal/.zshrc'] // Stat object
        for my zshrc.
            monitor.on("created", function (f, stat) {
              // Handle new files
           })
          monitor.on("changed", function (f, curr, prev) {
             // Handle file changes
           })
            monitor.on("removed", function (f, stat) {
             // Handle removed files
           })
            monitor.stop(); // Stop watching 
        })
    

回复 · 0

发表回复

你可以在回复中 @ 其他人