How to read a directory and know the files type?

Viewed 1335

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?

2 Answers

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());
    });
})

In the files string array couldn't you look for the file extension and determine that.

Related