I can't seem to get any search results that explain how to do this.
All I want to do is be able to know if a given path is a file or a directory (folder).
js? To check if a path is a directory in Node. js, we can use the stat() (asynchronous execution) function or the statSync() (synchronous execution) function from the fs (filesystem) module and then use the isDirectory() method returned from the stats object.
Any Node. Js version. const fs = require("fs"); let path = "/path/to/something"; fs. lstat(path, (err, stats) => { if(err) return console.
isFile() method returns true if the file path is File, otherwise returns false. The stats. isDirectory() method returns true if file path is Directory, otherwise returns false.
__dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file.
The following should tell you. From the docs:
fs.lstatSync(path_string).isDirectory()
Objects returned from fs.stat() and fs.lstat() are of this type.
stats.isFile() stats.isDirectory() stats.isBlockDevice() stats.isCharacterDevice() stats.isSymbolicLink() // (only valid with fs.lstat()) stats.isFIFO() stats.isSocket()
The above solution will throw
an Error
if; for ex, the file
or directory
doesn't exist.
If you want a true
or false
approach, try fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory();
as mentioned by Joseph in the comments below.
We can use the new fs.promises API
const fs = require('fs').promises; (async() => { const stat = await fs.lstat('test.txt'); console.log(stat.isFile()); })().catch(console.error)
Here's how you would detect if a path is a file or a directory asynchronously, which is the recommended approach in node. using fs.lstat
const fs = require("fs"); let path = "/path/to/something"; fs.lstat(path, (err, stats) => { if(err) return console.log(err); //Handle error console.log(`Is file: ${stats.isFile()}`); console.log(`Is directory: ${stats.isDirectory()}`); console.log(`Is symbolic link: ${stats.isSymbolicLink()}`); console.log(`Is FIFO: ${stats.isFIFO()}`); console.log(`Is socket: ${stats.isSocket()}`); console.log(`Is character device: ${stats.isCharacterDevice()}`); console.log(`Is block device: ${stats.isBlockDevice()}`); });
Note when using the synchronous API:
When using the synchronous form any exceptions are immediately thrown. You can use try/catch to handle exceptions or allow them to bubble up.
try{ fs.lstatSync("/some/path").isDirectory() }catch(e){ // Handle error if(e.code == 'ENOENT'){ //no such file or directory //do something }else { //do something else } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With