本文介绍了获取目录 nodejs 中的所有目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我希望这会是一件简单的事情,但我找不到任何可以这样做的东西.

I was hoping this would be a simple thing, but I cannot find anything out there to do so.

我只想获取给定文件夹/目录中的所有文件夹/目录.

I just want to get all folders/directories within a given folder/directory.

例如:

<MyFolder>
|- SomeFolder
|- SomeOtherFolder
|- SomeFile.txt
|- SomeOtherFile.txt
|- x-directory

我希望得到一个数组:

["SomeFolder", "SomeOtherFolder", "x-directory"]

或者上面的路径,如果这是它的服务方式...

Or the above with the path if that was how it was served...

那么是否已经存在可以执行上述操作的任何东西?

So does anything already exist to do the above?

推荐答案

承诺

const { promises: { readdir } } = require('fs')

const getDirectories = async source =>
  (await readdir(source, { withFileTypes: true }))
    .filter(dirent => dirent.isDirectory())
    .map(dirent => dirent.name)

回调

const { readdir } = require('fs')

const getDirectories = (source, callback) =>
  readdir(source, { withFileTypes: true }, (err, files) => {
    if (err) {
      callback(err)
    } else {
      callback(
        files
          .filter(dirent => dirent.isDirectory())
          .map(dirent => dirent.name)
      )
    }
  })

同步返回

const { readdirSync } = require('fs')

const getDirectories = source =>
  readdirSync(source, { withFileTypes: true })
    .filter(dirent => dirent.isDirectory())
    .map(dirent => dirent.name)

这篇关于获取目录 nodejs 中的所有目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 00:14