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


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,没有给出什么具体异常或提示信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dreamer who

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值