9

I can call

fs.readdirSync("C:\\", { withFileTypes: true })

and get array of fs.Dirent, but they look like

> fs.readdirSync("C:\\", { withFileTypes: true })[32]
Dirent { name: 'Windows', [Symbol(type)]: 2 }
> fs.readdirSync("C:\\", { withFileTypes: true })[21]
Dirent { name: 'pagefile.sys', [Symbol(type)]: 1 }
> fs.readdirSync("C:\\", { withFileTypes: true })[10]
Dirent { name: 'Documents and Settings', [Symbol(type)]: 3 }

So there is a name and and type, but the type is hidden under Symbol(type) and I can't find any information how to get it from there.

Of course I can use a hack like

> x = fs.readdirSync("C:\\", { withFileTypes: true })[10]
Dirent { name: 'DoYourData iCloud Backup', [Symbol(type)]: 3 }
> x[Object.getOwnPropertySymbols(x)[0]]
3

But that seems strange.

If it's hidden for purpose, and there is nothing public except name, then I don't understand why do we have a special flag in option to get an object instead of simple string.

screenshot

Qwertiy
  • 19,681
  • 15
  • 61
  • 128

2 Answers2

17

There are methods for checking object for special purposes. In documentation they are listed right after Dirent class.

Here is an example of using them:

var methods = ['isBlockDevice', 'isCharacterDevice', 'isDirectory', 'isFIFO', 'isFile', 'isSocket', 'isSymbolicLink'];

var res = fs.readdirSync("C:\\", { withFileTypes: true }).map(d => {
  var cur = { name: d.name }
  for (var method of methods) cur[method] = d[method]()
  return cur
})

console.table(res)

screenshot

Qwertiy
  • 19,681
  • 15
  • 61
  • 128
7

It's returning a Dirent (https://nodejs.org/api/fs.html#fs_class_fs_dirent)

The Dirent allows you to do stuff like this:

const results = fs.readdirSync("c:\\temp", { withFileTypes: true });
results.forEach(function(result) {
   console.log(result.name);
   console.log(` - isFile: ${result.isFile()}`);
   console.log(` - isDirectory: ${result.isDirectory()}`);
});
David
  • 3,488
  • 2
  • 21
  • 21