Reputation: 10965
I just ran into an odd situation that should not happen often, but I would like to prevent it from ever happening again.
I have a chunk of code that creates a deep dive directory list of all the files in a source folder and all of its children folders.
In general this has never been a problem, until today.
I had a fellow dev that accidentally set a symlink of a sub folder to point back at the parent folder. This caused my deep dive to recuse until it crashed.
For example:
topfolder
topfolder/sub1 - real folder
topfolder/sub2 - symlink back to topfolder
My code read all the files in topfolder
and then all files in topfolder/sub1
with no problems. Then, since topfolder/sub2
points back to topfolder
I read all the files in topfolder/sub2
, which are the same as in topfolder
and then topfolder/sub2/sub1
and then topfolder/sub2/sub2
and on to topfolder/sub2/sub2/sub2
, etc.
Is there a way, in node.js to determine the destination of a symlink? I figure if I can create a list of folders I have read and, when running into the symlink above, I determine that the destination is really a folder I have already read then I just skip that folder.
Thanks in advance...
Upvotes: 2
Views: 1057
Reputation: 4476
You have two choices (The Node documentation can be hard to use, so I also supply links to geeksforgeeks.) :
Example with readlink:
fs.readlink(fullPath, (err, linkString) => {
if (err) {
console.error(err);
} else {
console.log('LINK STRING', linkString);
}
});
With readlinkSync:
const linkString = fs.readlinkSync(fullPath);
debug('LINK STRING', linkString);
Upvotes: 1
Reputation: 2161
Is there a way, in node.js to determine the destination of a symlink?
Yes. fs.readlink(dir)
will return the destination of the symlink if it is one, an error otherwise.
fs.readlink("sub2", function(err, destination){
if(err)
//sub2 is not a symlink, proceed to go into it
else if(destination)
//sub2 is a symlink, check if 'destination' is a folder we have already been through
});
Upvotes: 3