我正在尝试编写一个从给定起始目录创建树的函数。换句话说,我选择一个目录,然后该函数将绝对映射该特定目录中的所有内容。我以前从未做过这样的事情,但是我已经接近预期的输出。但是,我不确定我要去哪里哪里。
起始目录
> Test Root
> 1a
> 1b
> 2a
> 2b
> 2c
> 1c
> 2a
> 1d
> 2a
> 2b
> testfile.txt
输出
第一个级别不错。第二层几乎不错,但是由于某种原因,它正在复制parent
属性并创建另一个嵌套对象。它还总是插入type
属性。我曾尝试删除constructor
中的属性,但输出结果令人困惑。
{
"parent": null,"path": "C:\\Users\\Anthony\\Desktop\\Test Root","name": "Test Root","kids": [
{
"parent": {
"parent": "C:\\Users\\Anthony\\Desktop\\Test Root","path": "C:\\Users\\Anthony\\Desktop\\Test Root\\1a","name": "1a","kids": []
},"type": "fileType"
},{
"parent": {
"parent": "C:\\Users\\Anthony\\Desktop\\Test Root","path": "C:\\Users\\Anthony\\Desktop\\Test Root\\1b","name": "1b","kids": [
{
"parent": {
"parent": "C:\\Users\\Anthony\\Desktop\\Test Root\\1b","path": "C:\\Users\\Anthony\\Desktop\\Test Root\\1b\\2a","name": "2a","kids": []
},"type": "fileType"
},{
"parent": {
"parent": "C:\\Users\\Anthony\\Desktop\\Test Root\\1b","path": "C:\\Users\\Anthony\\Desktop\\Test Root\\1b\\2b","name": "2b","path": "C:\\Users\\Anthony\\Desktop\\Test Root\\1b\\2c","name": "2c","type": "fileType"
}
]
},"path": "C:\\Users\\Anthony\\Desktop\\Test Root\\1c","name": "1c","kids": [
{
"parent": {
"parent": "C:\\Users\\Anthony\\Desktop\\Test Root\\1c","path": "C:\\Users\\Anthony\\Desktop\\Test Root\\1c\\2a","path": "C:\\Users\\Anthony\\Desktop\\Test Root\\1d","name": "1d","kids": [
{
"parent": {
"parent": "C:\\Users\\Anthony\\Desktop\\Test Root\\1d","path": "C:\\Users\\Anthony\\Desktop\\Test Root\\1d\\2a",{
"parent": {
"parent": "C:\\Users\\Anthony\\Desktop\\Test Root\\1d","path": "C:\\Users\\Anthony\\Desktop\\Test Root\\1d\\2b","path": "C:\\Users\\Anthony\\Desktop\\Test Root\\testfile.txt","name": "testfile.txt","type": "fileType"
},"type": "fileType"
}
]
}
功能
async function createTree(root){
const
Node = class {
constructor(parent,path,name,fifo){
this.parent = parent
this.path = path
this.name = name
fifo ? this.kids = [] : this.type = 'fileType'
}
addChild(parent,fifo){
this.kids.push(new Node(parent,fifo))
}
},traverse = async function(node,path){
const childPaths = await fsp.readdir(path)
for (const childPath of childPaths){
const
name = childPath,stats = await fsp.stat(join(path,childPath))
let
fifo
if (stats.isDirectory()) fifo = 1
else if (stats.isFile()) fifo = 0
const
childNode = new Node(path,join(path,childPath),fifo)
node.addChild(childNode)
traverse(childNode,childPath))
}
},rootName = root.slice(-1) === '\\' ? root.slice(0,1) : root.slice(root.lastIndexOf('\\')+1),tree = new Node(null,root,rootName,1)
traverse(tree,root)
setTimeout(function(){
console.log(JSON.stringify(tree,null,2))
},2500)
}
我刚刚意识到我的异步函数没有返回任何东西。明天我将不得不审视所有这一切。