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的实现方式不同而已。
我们要不要传递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,没有给出什么具体异常或提示信息。
版权声明:本文为博主原创文章,未经博主允许不得转载[http://blog.csdn.net/doctor_who2004]。
原文地址:http://blog.csdn.net/doctor_who2004/article/details/47361869