【问题标题】:Check if a symlink exists in node.js检查 node.js 中是否存在符号链接
【发布时间】:2014-06-08 19:40:01
【问题描述】:

关键问题是,如果符号链接指向的源文件不存在,但(现已失效的)符号链接仍然存在,那么 fs.exists(symlink) 将返回 false

这是我的测试用例:

var fs = require("fs");

var src = __dirname + "/src.txt";
var dest =  __dirname + "/dest.txt";

// create a file at src
fs.writeFile(src, "stuff", function(err) {
    // symlink src at dest
    fs.symlink(src, dest, "file", function(err) {
        // ensure dest exists
        fs.exists(dest, function(exists) {
            console.log("first exists", exists);
            // unlink src
            fs.unlink(src, function(err) {
                // ensure dest still exists
                fs.exists(dest, function(exists) {
                    console.log("exists after unlink src", exists);
                });
            });
        });
    });
});

这样的结果是:

first exists true
exists after unlink src false // symlink still exists, why is it false??

出现问题是因为我想在符号链接不存在时创建它,或者取消链接并在存在时重新创建它。目前我正在使用 fs.exists 执行此检查,但遇到了这个问题。除了 fs.exists 之外,还有什么替代方案不会出现同样的问题?

在 Windows 7 上的 CentOS Vagrant 上使用 Node 10。

【问题讨论】:

标签: node.js


【解决方案1】:

改用fs.lstatfs.readlinklstat 应该为您提供符号链接的统计对象,即使目标不存在,readlink 应该为您提供目标路径,因此您可以结合该逻辑来正确识别损坏的链接。

【讨论】:

  • 嗯,如果链接不存在,fs.lstat 似乎会抛出。
  • 对,但最初的问题不是询问链接本身不存在的情况。
猜你喜欢
  • 2011-08-11
  • 2019-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-02
  • 2012-06-19
  • 2013-08-28
相关资源
最近更新 更多