递归搜索节点中指定目录名的子目录 [英] Recursively search through sub directories for specified directory name in node

查看:32
本文介绍了递归搜索节点中指定目录名的子目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的目录结构:

/git
    /content
        /repo1
        /repo2
        /repo3
    /modules
        /repo4
        /repo5
    /tools
        /project
            /repo6
            /repo7
        /test
            /repo8
            /repo9

我希望能够通过传递存储库名称来找到特定存储库的路径:

I'd like to be able to find the path to a particular repo just by passing the repo name:

searchDirForSubdir('/git', 'repo7'); // expected to return /git/tools/project/repo7

我现在拥有的函数(如下)返回 undefined,即使 console.log 调用吐出正确的路径.我知道我搞砸了递归,但无法弄清楚我做错了什么.

The function I have at the moment (below) returns undefined, even though the console.log call spits out the correct path. I know I'm messing up the recursion, but can't work out what I'm doing wrong.

function searchDirForSubdir (dirToSearch, needle, depth = 0) {
    const DEPTH_LIMIT = 4;
    const fs = require('fs');
    for (let entry of fs.readdirSync(dirToSearch)) {
        if (depth + 1 <= DEPTH_LIMIT) {
            let fullPath = `${dirToSearch}/${entry}`;
            if (!entry.startsWith('.')
                && fs.lstatSync(fullPath).isDirectory()
            ) {
                if (entry == needle) {
                    console.log(fullPath);
                    return fullPath;
                } else {
                    searchDirForSubdir (fullPath, needle, depth + 1);
                }
            }
        }
    }
}

推荐答案

你在 searchDirForSubdir (fullPath, Needle, depth + 1); 行之前缺少一个 return 子句;,如果它返回了一些东西.

you are missing a return clause before the line searchDirForSubdir (fullPath, needle, depth + 1);, if it returned something.

您的代码已修复:

function searchDirForSubdir(dirToSearch, needle, depth = 0) {
    const DEPTH_LIMIT = 4;
    const fs = require('fs');
    for (let entry of fs.readdirSync(dirToSearch)) {
        if (depth + 1 <= DEPTH_LIMIT) {
            let fullPath = `${dirToSearch}/${entry}`;
            if (!entry.startsWith('.')
                 && fs.lstatSync(fullPath).isDirectory()) {
                if (entry == needle) {
                    return fullPath;
                } else {
                    const found = searchDirForSubdir(fullPath, needle, depth + 1);
                    if (found)
                        return found;
                }
            }
        }
    }
}

这篇关于递归搜索节点中指定目录名的子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆