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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With