Node.js: Check if file is an symbolic link when iterating over directory with 'fs'

13,258

Solution 1

You can use fs.lstat and then call statis.isSymbolicLink() on the fs.Stats object that's passed into your lstat callback.

fs.lstat('myfilename', function(err, stats) {
    console.log(stats.isSymbolicLink());
});

Solution 2

Seems like you can use isSymbolicLink()

const files = fs.readdirSync(dir, {encoding: 'utf8', withFileTypes: true});
files.forEach((file) => {
  if (file.isSymbolicLink()) {
    console.log('found symlink!');
  }
}
Share:
13,258
james_womack
Author by

james_womack

I started programming via JScript in IE 4, 1998. iOS/iPhoneOS in 2008, Node in 2011. I love teaching people new technologies and want to leverage technology to make everyday life better for everyone. Currently, I focus on: Improving dev + customer happiness by integrating cutting-edge tech into existing stacks at Netflix. This also is increasing frequency of feature deployments while decreasing bugs Implementing best practices in cross-functional multi-team dev environments, to produce more cohesive experiences for the customer Architecting full-stack systems that utilize bluetooth & cameras on mobile devices to deliver modern, friction-less customer experiences Client/server/database sharing of JavaScript code—I started on this in early 2012 along with some great programmers at Amco-IES and continued this work in ソニー

Updated on June 06, 2022

Comments

  • james_womack
    james_womack about 2 years

    Supervisor is a package for Node.js that monitors files in your app directory for modifications and reloads the app when a modification occurs.

    This script interprets symbolic links as regular files and logs out a warning. I would like to fork Supervisor so that either this can be fixed entirely or that a more descriptive warning is produced.

    How can I use the File System module of Node.js to determine if a given file is really an symbolic link?