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

前端 未结 1 1888
暖寄归人
暖寄归人 2021-01-18 20:20

I am trying to monitor a file that is (soft) symlink\'ed with node.js\' watchFile() with the following code:

var fs=require(\'fs\')
    , file= \'./somesymli         


        
相关标签:
1条回答
  • 2021-01-18 20:57

    You could use fs.readlink:

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

    Of course, you could get fancier and write a little wrapper that can watch either the file or it's link, so you don't have to think about it.

    UPDATE: Here's such a wrapper, for the future:

    /** Helper for watchFile, also handling symlinks */
    function watchFile(path, callback) {
        // Check if it's 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's not a symlink, just watch it
                fs.watch(path, callback);
            }
        });
    }
    
    0 讨论(0)
提交回复
热议问题