1

Situation

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.

My question

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...

Intervalia
  • 8,536
  • 1
  • 21
  • 47

1 Answers1

2

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
});
MadWard
  • 1,705
  • 1
  • 7
  • 15