Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a symlink exists in node.js

Tags:

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.

like image 947
Nucleon Avatar asked Apr 23 '14 19:04

Nucleon


1 Answers

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.

like image 83
Peter Lyons Avatar answered Nov 10 '22 04:11

Peter Lyons