【问题标题】:How to watch symlink'ed files in node.js using watchFile()如何使用 watchFile() 在 node.js 中观看符号链接的文件
【发布时间】:2012-03-10 23:50:29
【问题描述】:

我正在尝试使用以下代码监视使用 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'); 
    } 
});

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

所以我的问题是如何使用 watchFile() 在 node.js 中观看符号链接的文件。提前谢谢大家。

【问题讨论】:

    标签: node.js


    【解决方案1】:

    你可以使用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);
            }
        });
    }
    

    【讨论】:

    • 正是我想要的,非常感谢。我希望我可以投票给你的答案,但我必须至少有 15 个声望才能做到这一点。将您的答案标记为已接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 2019-01-24
    • 2011-04-17
    • 2013-09-19
    • 2012-12-14
    • 1970-01-01
    相关资源
    最近更新 更多