如果沒有任何目錄,我正在制作一個包含檔案目錄和檔案名的嵌套物件
預期的 :
{ dir_name : "test",
sub_dir : {dir_name : "test2",
sub_dir : {dir_name : "test3".
sub_dir: [0001.dcm, 0002.dcm, 003.dcm]}}
}
我的結果:
{ dir_name: 'test', sub_dir: Promise { <pending> } }
我的代碼:
async function make_dir(FilePath){
return new Promise((resolve, reject) => {
fs.readdir(FilePath, async (err,files) => {
var arr = [];
files.forEach((file) => {
if (!file.includes(".dcm")){
var container = { dir_name: file,
sub_dir: {}}
container.sub_dir = make_dir(FilePath file '/')
resolve(container)
}
else{
arr.push(file);
}
});
resolve(arr)
})
})
}
uj5u.com熱心網友回復:
建議的結構無效,因為一個目錄可以有一個或多個子目錄 -
{
dir: "foo",
sub_dir: { ... },
sub_dir: { ... }, // cannot reuse "sub_dir" key
}
這是一種可以構建這樣的樹的替代方法-
{
"test1":
{
"test2":
{
"test3":
{
"0001.dcm": true,
"0002.dcm": true,
"003.dcm": true
}
}
}
}
fs/promises 和 fs.Dirent
這是一個使用 Node 的快速fs.Dirent物件和fs/promises模塊的高效、非阻塞程式。這種方法允許您跳過每條路徑上的浪費fs.exist或fs.stat呼叫 -
// main.js
import { readdir } from "fs/promises"
import { join, basename } from "path"
async function* tokenise (path = ".")
{ yield { dir: path }
for (const dirent of await readdir(path, { withFileTypes: true }))
if (dirent.isDirectory())
yield* tokenise(join(path, dirent.name))
else
yield { file: join(path, dirent.name) }
yield { endDir: path }
}
async function parse (iter = empty())
{ const r = [{}]
for await (const e of iter)
if (e.dir)
r.unshift({})
else if (e.file)
r[0][basename(e.file)] = true
else if (e.endDir)
r[1][basename(e.endDir)] = r.shift()
return r[0]
}
async function* empty () {}
現在createTree僅僅是組合tokenise和parse-
const createTree = (path = ".") =>
parse(tokenise(path))
createTree(".")
.then(r => console.log(JSON.stringify(r, null, 2)))
.catch(console.error)
讓我們獲取一些示例檔案,以便我們可以看到它的作業 -
$ yarn add immutable # (just some example package)
$ node main.js
{
".": {
"main.js": true,
"node_modules": {
".yarn-integrity": true,
"immutable": {
"LICENSE": true,
"README.md": true,
"contrib": {
"cursor": {
"README.md": true,
"__tests__": {
"Cursor.ts.skip": true
},
"index.d.ts": true,
"index.js": true
}
},
"dist": {
"immutable-nonambient.d.ts": true,
"immutable.d.ts": true,
"immutable.es.js": true,
"immutable.js": true,
"immutable.js.flow": true,
"immutable.min.js": true
},
"package.json": true
}
},
"package.json": true,
"yarn.lock": true
}
}
我希望你喜歡閱讀這篇文章。有關使用異步生成器的附加說明和其他方法,請參閱此問答。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/315810.html
標籤:javascript 目的 递归 承诺
