Reputation: 2766
If we want to read a folder, we can:
const fs = require('fs')
let folderName = 'Any_folder_name'
fs.readdir(folderName,(err,files)=>{
if (err) throw err;
console.log(files)
// this is a files' name list in this folder
})
but the return value is only a list of files name. Such as ['README.md','src']
.
But I want to konw which is a file and which is a folder. How to do this?
I know we can use a loop to this list and fs.stats
to confirm which is a folder.
But I want to know if there is a more effcient way to do this?
Upvotes: 6
Views: 5197
Reputation: 357
In the files string array couldn't you look for the file extension and determine that.
Upvotes: 0
Reputation: 6058
You can use {withFileTypes: true}
options, the result will contain fs.Dirent objects.
Try:
fs.readdir(folderName, {withFileTypes: true}, (err, files) => {
if (err) throw err;
files.forEach(file => {
console.log(file.isDirectory());
});
})
Upvotes: 5