如何从 fs.Dirent 获取类型?

Qwe*_*tiy 6 javascript fs node.js

我可以打电话

fs.readdirSync("C:\\", { withFileTypes: true })
Run Code Online (Sandbox Code Playgroud)

并获得数组fs.Dirent,但它们看起来像

> 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 }
Run Code Online (Sandbox Code Playgroud)

所以有一个名称和类型,但类型隐藏在 Symbol(type) 下,我找不到任何信息如何从那里获取它。

当然,我可以使用像

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

但这似乎很奇怪。

如果它是出于目的而隐藏的,并且除了名称之外没有任何公共内容,那么我不明白为什么我们在选项中使用特殊标志来获取对象而不是简单的字符串。

截屏

Qwe*_*tiy 10

有一些方法可以为特殊目的检查对象。在文档中,它们列在Dirent class 之后

以下是使用它们的示例:

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)
Run Code Online (Sandbox Code Playgroud)

截屏

  • 投票只是为了展示 `console.table` 的使用;-p (3认同)

Dav*_*vid 7

它返回一个 Dirent ( https://nodejs.org/api/fs.html#fs_class_fs_dirent )

Dirent 允许你做这样的事情:

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()}`);
});
Run Code Online (Sandbox Code Playgroud)