2012-02-20 68 views
4

我想监视的文件是(软)与node.js的watchFile(symlink'ed)用下面的代码:如何观看使用watchFile()在node.js中symlink'ed文件

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'); 
    } 
}); 

在上面的代码中,./somesymlink是一个(软)符号链接到/path/to/the/actual/file。 当对/ path/to/the/actual/file进行更改时,不会触发任何事件。我必须用/ path/to/the/actual/file替换符号链接,以使其工作。在我看来,watchFile无法观看符号链接的文件。当然,我可以通过使用spawn + tail方法来完成这项工作,但我不希望使用该路径,因为它会引入更多开销。

所以我的问题是我怎样才能使用watchFile()在node.js中观看符号链接的文件。预先感谢乡亲们。

回答

23

你可以使用fs.readlink

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

当然,你可以让爱好者和写一个小包装,可以观看任何文件或它的链接,所以你不必去想它。

UPDATE:这里有这样的包装,为未来:

/** 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); 
     } 
    }); 
} 
+1

正是我一直在寻找,多谢。我希望我可以对你的答案进行投票,但为了做到这一点,我必须至少有15个声望。将您的答案标记为已接受。 – ricochen 2012-02-20 17:34:41

+0

这很酷,让我们希望别人喜欢它。 ;) – 2012-02-20 17:43:25