javascript:如何在类似文件树的结构中创建目录?

javascript:如何在类似文件树的结构中创建目录?,javascript,node.js,Javascript,Node.js,我有下面列出的代码。所有的“树”类都很好。我需要“makekDir”函数的帮助(在节点类中),它应该创建新的子树(目录)。“makekDir”函数中的此代码This.findNode(filepath)始终返回null。我找不到如何修理它。有人能帮忙吗,或者给我建议如何修复它吗?对不起,代码太多了,我不知道如果我只发布节点类,这是可以理解的吗 import path from 'path'; //this class works fine class Tree { constructor(

我有下面列出的代码。所有的“树”类都很好。我需要“makekDir”函数的帮助(在节点类中),它应该创建新的子树(目录)。“makekDir”函数中的此代码
This.findNode(filepath)
始终返回null。我找不到如何修理它。有人能帮忙吗,或者给我建议如何修复它吗?对不起,代码太多了,我不知道如果我只发布节点类,这是可以理解的吗

import path from 'path';

//this class works fine
class Tree {
  constructor(key, meta, parent) {
    this.parent = parent;
    this.key = key;
    this.meta = meta;
    this.children = new Map();
  }

  getKey() {
    return this.key;
  }

  getMeta() {
    return this.meta;
  }

  addChild(key, meta) {
    const child = new Tree(key, meta, this);
    this.children.set(key, child);

    return child;
  }

  getChild(key) {
    return this.children.get(key);
  }

  hasChild(key) {
    return this.children.has(key);
  }

  getDeepChild(dirs = []) {
    if (dirs.length === 0 || !Array.isArray(dirs)) {
      console.log('not array');
      return null;
    }
    const [first, ...rest] = dirs;
    console.log(first, ...rest);
    console.log (this);
    if (this.hasChild(first)) {
      return rest.length === 0 
        ? this.getChild(first)
        : this.getChild(first).getDeepChild(rest); 
    }
    return null;
  }
}

class Node {
  constructor() {
    this.tree = new Tree('/', { type: 'dir' });
  }

  ///// I need help with this function
  makekDir(filepath) {
    const { dir } = path.parse(filepath);
    const subtree = this.findNode(filepath);
    return subtree.addChild(dir, { type: 'dir' });
  }
 ///// 

  findNode(filepath) {
    const parts = filepath.split(path.sep).filter((item) => item !== '');
    return parts.length === 0 ? this.tree : this.tree.getDeepChild(parts);
  }
}

console.log(new Node().makekDir('/etc'));

您没有考虑
this.tree.getDeepChild(parts)
可能返回
null
,这导致您对该null值调用
subtree.addChild
。它总是返回
null
b/c
(新树('/',{type:'dir'})).getDeepChild(['etc'])
始终返回
null
。你就是这么编的。嗯,你说得对。当树为空时,“getDeepChild”返回
null
。它应该返回最深的现有子级
(新树('/',{type:'dir'}))。getDeepChild(['etc',vars',test'])
应该返回树的“test”,就像
/etc/vars/test/
不知道如何修复它一样。但我会努力的。泰。