您的位置:首页 > Web前端 > Node.js

Node.js文件模块fs监视文件变化

2015-08-08 21:01 1126 查看

Node.js文件模块fs监视文件变化

Node中文件模块fs监视文件的函数源码如下:

fs.watch = function(filename) {
  nullCheck(filename);
  var watcher;
  var options;
  var listener;

  if (util.isObject(arguments[1])) {
    options = arguments[1];
    listener = arguments[2];
  } else {
    options = {};
    listener = arguments[1];
  }

  if (util.isUndefined(options.persistent)) options.persistent = true;
  if (util.isUndefined(options.recursive)) options.recursive = false;

  watcher = new FSWatcher();
  watcher.start(filename, options.persistent, options.recursive);

  if (listener) {
    watcher.addListener('change', listener);
  }

  return watcher;
};


该函数显示要传参filename, 而且第一行验证文件名参数不能为空。不过,我们可以选择传递三个参数或二个参数,代码:

if (util.isObject(arguments[1])) {
    options = arguments[1];
    listener = arguments[2];
  } else {
    options = {};
    listener = arguments[1];
  }


会根据参数个数做变化。这种js函数,相当于java中的变参函数:Type... args,args可以为空。

只不过js这个变参和java的实现方式不同而已。

我们要不要传递listener监听回调函数,还需要看源码或者API说明,毕竟我们不能从显示的js传参看出信息。

[函数设计:一定要传的参数,函数显示说明,并验证参数非null,其它可传不传的参数从arguments[]数组获取]

监视文件变化代码:

/**
 * Created by doctor on 15-8-8.
 */

const fs = require('fs');
var fileName = 't.txt';
fs.watch(fileName,( function () {
    var count = 0;
    return function(){
        count++;
        console.log("文件" + fileName + " 内容刚刚改变。。第" + count + "次" );
    };
})());
console.log("watching file...");


验证一下:在上面代码相同目录下建立一个文件:t.txt.

执行:

[doctor@localhost ebook-NodejsTheRightWay]$ node Chapter2Code.js 
watching file...


我们对文件操作改变:

[doctor@localhost ebook-NodejsTheRightWay]$ touch t.txt 
[doctor@localhost ebook-NodejsTheRightWay]$ touch t.txt 
[doctor@localhost ebook-NodejsTheRightWay]$ echo doctor >> t.txt 
[doctor@localhost ebook-NodejsTheRightWay]$


结果:

[doctor@localhost ebook-NodejsTheRightWay]$ node Chapter2Code.js 
watching file...
文件t.txt 内容刚刚改变。。第1次
文件t.txt 内容刚刚改变。。第2次
文件t.txt 内容刚刚改变。。第3次




不过,我用vim编辑后保存,或者其它图形界面编辑器编辑,显示不正常。是Node fs底层模块不支持,还是有bug,没有给出什么具体异常或提示信息。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: