var fs = require('fs');

var filePath = 'D:\\example\\file.txt';

var file = fs.readFileSync(filePath);

console.log('Initial File content : ' + file);





fs.watchFile(filePath, function() {

console.log('File Changed ...');

file = fs.readFileSync(filePath);

console.log('File content at : ' + new Date() + ' is

' + file);

});

var fs = require('fs');

var filePath = 'D:\\example\\file.txt';

var file = fs.readFileSync(filePath);

console.log('Initial File content : ' + file);





fs.watch(filePath, function(event, filename) {

if(filename){

console.log('Event : ' + event);

console.log(filename + ' file Changed ...');

file = fs.readFileSync(filePath);

console.log('File content at : ' + new Date() + ' is

' + file);

}

else{

console.log('filename not provided')

}

});

In this post we are going to discuss about monitoring a file for all modifications in node.js. If you want to know the changes made to the files in the file system, then themodule of node.js has solution for it. For monitoring a file for modificationmodule in node.js has given us two optionand- It watches the changes on file. The callback cfunction will be called each time the file is accessed. Options are optional where you have two values to set persistent and interval. Persistent indicates that the process should continue as long as the files are watch and Interval indicates how often target should be checked. The default value of persistent is true and interval is 5007.The initial file content is Hello World !!! then after some time we will change the content to Hello !!! and then to Hello World Again !!!. The output is shown below.fs.watchFile() is deprecated. Use fs.watch() instead.- Like fs.warchFile it also watches the change on file. It has a return object which will return an object of fs.FSWatcher. Options are optional where you have two values to set persistent and recursive. Persistent indicates that the process should continue as long as the files are watch and recursive indicates whether only current directory should be watched or all sub-directories to be watched. The default value of persistent is true and recursive is false. The callback cfunction is also optional, if it is there it will take two arguments event and filename. Event is eitherorwhereas filename is the name of the file.The initial file content is Hello World !!! then after some time we will change the content to Hello !!!. The output is shown below.There is awhen usingis that it outputs multiple times for a single change. ( https://github.com/nodejs/node-v0.x-archive/issues/2126 ). Please Like and Share CodingDefined.com Blog, if you find it interesting and helpful.