Shuai Li
Shuai Li

Reputation: 2766

How to read a directory and know the files type?

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

Answers (2)

Gurpreet_Carmel_5
Gurpreet_Carmel_5

Reputation: 357

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

Upvotes: 0

Ihor Sakailiuk
Ihor Sakailiuk

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

Related Questions