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

我试图用下面的代码监视一个与soft.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'); } }); 

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

所以我的问题是如何使用watchFile()在node.js中查看符号链接的文件。 预先感谢人们。

你可以使用fs.readlink :

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

当然,你可以更有趣,写一个可以看文件或链接的小包装,所以你不必考虑。

更新:这是未来的封装:

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