node. js file Module FS Monitor file Changes
The functions of the file module fs monitoring file in node source code are as follows:
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;};
The function displays the filename to be passed, and the first row verifies that the file name parameter cannot be empty. However, we can choose to pass three parameters or two parameters, code:
if (Util.isobject (Arguments[1])) { options = arguments[1]; Listener = arguments[2]; } else { options = {}; Listener = arguments[1]; }
varies according to the number of parameters. This JS function is equivalent to the variable parameter function in Java: Type ... args,args can be empty.
Only js this parameter and Java implementation of different ways.
We should not pass listener monitoring callback function, but also need to look at the source code or API description, after all, we can not see the information from the display of JS parameters.
[function Design: Must pass the parameters, function display description, and verify that the parameter is not NULL, other arguments can be passed from the arguments[] array get]
Monitor file Change code:
/** * 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 ("file" + filename + "content has just changed. "+ Count +" Times "); };}) ()); Console.log ("Watching file ...");
Verify: Create a file in the same directory as the above code: T.txt.
Perform:
[Email protected] ebook-nodejstherightway]$ node Chapter2code.js watching file ...
We changed the file operation:
Results:
[Email protected] ebook-nodejstherightway]$ node Chapter2code.js watching file ... File t.txt content just changed. The 1th time file t.txt content has just changed. The 2nd time file T.txt content has just changed. 3rd time
However, I use VIM to edit the save, or other graphical interface editor, the display is not normal. Node FS is not supported by the underlying module, or there is a bug, no specific exception or prompt information.
Copyright NOTICE: This article for Bo Master original article, without BO Master permission cannot reprint [http://blog.csdn.net/doctor_who2004].
Node. js file Module FS Monitor file changes