简体   繁体   English

如何使用watchFile()在node.js中观看符号链接文件

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

I am trying to monitor a file that is (soft) symlink'ed with node.js' watchFile() with the following code: 我试图使用以下代码监视与node.js'watchFile()(软)符号链接的文件:

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) symlink to /path/to/the/actual/file . 在上面的代码中,。/ somesymlink/ path / to / / / file的(软)符号链接。 When changes are made to the /path/to/the/actual/file, no event is fired. 当对/ path / to / / / /文件进行更改时,不会触发任何事件。 I have to replace the symlink with /path/to/the/actual/file to make it work. 我必须用/ path / to / / / / file替换符号链接才能使它工作。 It seems to me that watchFile is not able to watch symlink'ed files. 在我看来,watchFile无法观看符号链接的文件。 Of course I could make this work by using spawn+tail method but I prefer not to use that path as it would introduce more overhead. 当然我可以通过使用spawn + tail方法来完成这项工作,但我不想使用该路径,因为它会引入更多开销。

So my question is how can I watch symlink'ed files in node.js using watchFile(). 所以我的问题是如何使用watchFile()在node.js中观看符号链接文件。 Thanks folks in advance. 提前谢谢大家。

You could use fs.readlink : 你可以使用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);
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM