如何修复Node类makekDir函数中findNode返回null的问题?
问题分析与修复方案
咱们先拆解下你代码里的核心问题:
当你调用new Node().makekDir('/etc')时,执行逻辑完全走偏了:
path.parse('/etc')返回的结果里,dir是'/',base是'etc'——你需要的是在/这个父目录下创建etc子目录,但你的代码却在找/etc这个还不存在的节点,自然返回null;- 退一步说,就算找到了节点,你用
dir(也就是'/')作为子节点的key去添加,逻辑也是完全错误的。
下面是修复后的完整代码,我标注了关键修改点:
import path from 'path'; // Tree类保持不变,运行正常 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; 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' }); } // 修复后的mkdir函数(顺便把多打的k改了,更规范) mkdir(filepath) { const { dir, base } = path.parse(filepath); // 先找到要创建目录的父节点(而不是找不存在的目标节点) const parentNode = this.findNode(dir); if (!parentNode) { throw new Error(`父目录 ${dir} 不存在,无法创建子目录`); } // 在父节点下添加新的子目录(用base作为目录名) return parentNode.addChild(base, { 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().mkdir('/etc'));
关键修改说明:
- 从
path.parse中同时提取dir(父目录路径)和base(要创建的目录名),这才是正确的拆分逻辑; - 调用
findNode(dir)获取父目录节点——比如创建/etc时,父目录是/,这个节点是存在的; - 增加了父节点存在性检查,避免后续无意义的报错;
- 最后在父节点下添加
base作为子节点,完成目录创建。
这样修改后,你的代码就能正常创建子目录树了。另外建议把函数名makekDir改成mkdir,符合通用命名习惯~
内容的提问来源于stack exchange,提问作者Lex27
相关产品推荐
相关产品推荐

