Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get type from fs.Dirent?

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)]: 2 }
> 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

like image 290
Qwertiy Avatar asked Oct 14 '19 19:10

Qwertiy


2 Answers

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

like image 74
Qwertiy Avatar answered Oct 20 '22 06:10

Qwertiy


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()}`);
});
like image 42
David Avatar answered Oct 20 '22 04:10

David