Owen Allen
Owen Allen

Reputation: 11978

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.

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. What is an alternative besides fs.exists which won't have this same problem?

Using Node 10 on CentOS Vagrant on Windows 7.

Upvotes: 14

Views: 11059

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146164

Try fs.lstat and fs.readlink instead. 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.

Upvotes: 15

Related Questions