使用 nodejs 获取目录中的所有递归目录



我想让给定目录中的所有目录同步。

<MyFolder>
|- Folder1
|- Folder11
|- Folder12
|- Folder2
|- File1.txt
|- File2.txt
|- Folder3
|- Folder31
|- Folder32

我希望得到一个数组:

["Folder1/Folder11", "Folder1/Folder12", "Folder2", "Folder3/Folder31", "Folder3/Folder32"]

这是我的代码:

const fs = require('fs');
const path = require('path');
function flatten(lists) {
return lists.reduce((a, b) => a.concat(b), []);
}
function getDirectories(srcpath) {
return fs.readdirSync(srcpath)
.map(file => path.join(srcpath, file))
.filter(path => fs.statSync(path).isDirectory());
}
function getDirectoriesRecursive(srcpath) {
return [srcpath, ...flatten(getDirectories(srcpath).map(getDirectoriesRecursive))];
}

有人会帮我解决上面的问题吗?

异步

这是一个使用Node的快速fs的高度优化版本。可怕的对象。这种方法允许您跳过昂贵的fs.existsSync,并在每条路径上fs.statSync调用 -

const { readdir } =
require ("fs/promises")
const { join } =
require ("path")
const dirs = async (path = ".") =>
Promise.all
( (await readdir (path, { withFileTypes: true }))
.map
( dirent =>
dirent .isDirectory ()
? dirs (join (path, dirent.name))
: []
)
)
.then
( results =>
[] .concat (path, ...results)
)

你这样用——

dirs ("MyFolder") .then (console.log, console.error)
<小时 />

同步

我们可以改用同步函数重写上面的函数 -

const { readdirSync } =
require ("fs")
const { join } =
require ("path")
const dirsSync = (path = ".") =>
[].concat
( path
, ...readdirSync (path, { withFileTypes: true })
.map
( dirent =>
dirent .isDirectory ()
? dirsSync (join (path, dirent.name))
: []
)
)

你这样用——

console .log (dirsSync ("MyFolder"))

这可以通过使用Array.prototype.flatMap进一步简化 -

const { readdirSync } =
require ("fs")
const { join } =
require ("path")
const dirsSync = (path = ".") =>
[ path
, ...readdirSync (path, { withFileTypes: true })
.flatMap
( dirent =>
dirent .isDirectory ()
? dirsSync (join (path, dirent.name))
: []
)
]

你快到了,你只需要避免files(不是目录(,所以getDirectoriesRecursive(srcpath)函数递归不会抛出错误。

这是最终getDirectoriesRecursive代码应该如何:

function getDirectoriesRecursive(srcpath) {
return [srcpath, ...flatten(getDirectories(srcpath).map((p) => {
try {
if (fs.existsSync(path)) {
if (fs.lstatSync(path).isDirectory()) {
return getDirectoriesRecursive(path);
}
}
} catch (err) {
console.error(err)
}
}).filter(p => p !== undefined))];
}

这是一个实时工作的Repl演示,用于显示"/opt"中的所有目录。

相关内容

  • 没有找到相关文章

最新更新