Search code examples
node.jsfs

How to determine if directory is a symbolic link


I ran fs.lstat and I get these stats for a directory:

Stats {
  dev: 16777220,
  mode: 16877,
  nlink: 8,
  uid: 501,
  gid: 20,
  rdev: 0,
  blksize: 4096,
  ino: 7366885,
  size: 272,
  blocks: 0,
  atime: 2017-04-16T23:18:17.000Z,
  mtime: 2017-04-16T23:14:49.000Z,
  ctime: 2017-04-16T23:14:49.000Z,
  birthtime: 2017-04-16T23:14:49.000Z }

How I can determine if this directory is a symbolic link?


Solution

  • I was logging the stats object with

    util.inspect(stats);
    

    but the methods for the stats object are on the __proto__ of the object:

    stats.isSymbolicLink() is the call to use

    You want to use fs.lstat() instead of fs.stat(), as the former will not follow the symbolic link. If you follow the symbolic link, eventually you will get to an actual directory, which would mean stats.isSymbolicLink() would always return false. But that's not really what we are looking for.

    So the answer is:

    fs.lstat(<path>, function(err,stats){
    
         if(stats.isSymbolicLink()){
              // do your thing
          }
    
    });