How to watch symlink 'files in node.js using watchFile () function

I am trying to control a (soft) symlink'ed file using node.js' watchFile () with the following code:

var fs=require('fs') , file= './somesymlink' , config= {persist:true, interval:1}; fs.watchFile(file, config, function(curr, prev) { if((curr.mtime+'')!=(prev.mtime+'')) { console.log( file+' changed'); } }); 

In the above code ./somesymlink is a (soft) symbolic link to / path / to / the / actual / file . When changes are made to the / path / to / the / actual / file file, the event does not fire. I need to replace the symlink with / path / to / the / actual / file for it to work. It seems to me that watchFile cannot watch symlink'ed files. Of course, I could do this work using the spawn + tail method, but I prefer not to use this path, since it will introduce additional overhead.

So my question is how can I watch symlink 'files in node.js using the watchFile () function. Thanks to the people in advance.

+4
source share
1 answer

You can use fs.readlink :

 fs.readlink(file, function(err, realFile) { if(!err) { fs.watch(realFile, ... ); } }); 

Of course, you could fall in love and write a small wrapper that can watch a file or link, so you don't need to think about it.

UPDATE: Here is a shell for the future:

 /** Helper for watchFile, also handling symlinks */ function watchFile(path, callback) { // Check if it a link fs.lstat(path, function(err, stats) { if(err) { // Handle errors return callback(err); } else if(stats.isSymbolicLink()) { // Read symlink fs.readlink(path, function(err, realPath) { // Handle errors if(err) return callback(err); // Watch the real file fs.watch(realPath, callback); }); } else { // It not a symlink, just watch it fs.watch(path, callback); } }); } 
+23
source

Source: https://habr.com/ru/post/1397461/


All Articles