Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 686
james_womack Avatar asked Jul 01 '12 18:07

james_womack


People also ask

How do you check if a file exists with fs?

The fs. existsSync() method allows you to check for the existence of a file by tracing if a specified path can be accessed from the current directory where the script is executed. It returns true when the path exists and false when it's not.

How do I validate a path in node JS?

Any Node. Js version. const fs = require("fs"); let path = "/path/to/something"; fs. lstat(path, (err, stats) => { if(err) return console.

Does Stat follow symlinks?

stat() does handle links, it just handles them differently - it follows the link and tells you about the file that it points to (which, as wich points out, is oftentimes what you want). You use stat() when you want links to behave in the "normal way", i.e. as the file they point at.


2 Answers

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()); }); 
like image 190
JohnnyHK Avatar answered Sep 18 '22 15:09

JohnnyHK


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!');   } } 
like image 36
Boris Yakubchik Avatar answered Sep 19 '22 15:09

Boris Yakubchik