简体   繁体   English

检查node.js中是否存在符号链接

[英]Check if a symlink exists in node.js

The key issue is that if the source file that a symlink points to does not exist, but the (now dead) symlink still exists then a fs.exists(symlink) will return false . 关键问题是,如果符号链接指向的源文件不存在,但(现在已死)符号链接仍然存在,则fs.exists(symlink)将返回false

Here is my test case: 这是我的测试用例:

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

The result of this is: 结果是:

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

The issue arises because I want to create a symlink if it doesn't exist, or unlink it and re-create it if it does. 出现这个问题是因为我想创建一个符号链接(如果它不存在),或者取消链接并重新创建它(如果存在)。 Currently I'm using fs.exists to perform this check, but ran into this problem. 目前我正在使用fs.exists来执行此检查,但遇到了这个问题。 What is an alternative besides fs.exists which won't have this same problem? 除了没有同样问题的fs.exists之外还有什么选择?

Using Node 10 on CentOS Vagrant on Windows 7. 在Windows 7上的CentOS Vagrant上使用节点10。

Try fs.lstat and fs.readlink instead. 请尝试使用fs.lstatfs.readlink lstat should give you a stats object for a symlink even if the target does not exist, and readlink should get you the path to the target, so you can combine that logic to correctly identify broken links. 即使目标不存在, lstat应该为符号链接提供stats对象, readlink应该为您提供目标路径,因此您可以组合该逻辑以正确识别损坏的链接。

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

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