使用require-all从目录和子目录中递归加载文件



我在目录和子目录中有 json 文件,我想与特定条件匹配,但我不知道如何使用子目录。

我正在使用全部要求来查找 json 文件:

const reqAll = require('require-all')({
  dirname: __dirname + '/resource',
  filter: /(.+).json$/,
  recursive: true
});

我的文件树是这样的:

MyDir
- file1.json
- SubDir
-- file2.json

打印reqAll将输出:

{ 
  file1: { 
    path: /first,
    body: ...some body
  },
  SubDir: { 
    file2: { 
      path: /second,
      body: ...some body
    } 
  } 
}

我最初使用以下过滤器来清除我的数据,因为我最初不使用子目录,但现在这样做是有意义的。

let source = Object.values(reqAll).filter(r => {
    return r.path === req.url;
}

其中req.url是我发送的 http 请求的 url.即:localhost:8080/first ,以便它与我在目录中的file1文件匹配。

问题是,当我提交localhost:8080/second时,我没有得到回应,因为我无法匹配file2因为这在子目录中。发送localhost:8080/SubDir/file2也不起作用。

有没有办法让我让它工作?

在你写的评论中:

因此,我将执行HTTP GET,localhost:8080/first,它应该返回file1对象的正文。这实际上适用于此终结点。但是,当我在本地主机:8080/秒上执行 HTTP GET 时,我无法取回正文。

为此,您需要递归搜索具有该path的条目,类似于以下行(请参阅注释(:

const repAll = { 
    file1: { 
        path: "/first"
    },
    SubDir: { 
        file2: { 
            path: "/second"
        },
        SubSubDir: {
            file3: {
                path: "/third"
            }
        }
    } 
};
const req = {};
function findEntry(data, path) {
    for (const value of Object.values(data)) {
        // Is this a leaf node or a container?
        if (value.path) {
            // Leaf, return it if it's a match
            if (value.path === path) {
                return value;
            }
        } else {
            // Container, look inside it recursively
            const entry = findEntry(value, path);
            if (entry) {
                return entry;
            }
        }
    }
    return undefined; // Just to be explicit
}
for (const url of ["/first", "/second", "/third", "fourth"]) {
    req.url = url;
    console.log(req.url + ":", findEntry(repAll, req.url));
}
.as-console-wrapper {
    max-height: 100% !important;
}

我添加了第二个子目录以确保递归继续工作,以及一个示例,说明如果您找不到匹配的路径,您将获得什么。

当然,您可以通过预先处理一次repAll来构建地图,然后重用地图,这将比这种线性搜索更快:

const repAll = { 
    file1: { 
        path: "/first"
    },
    SubDir: { 
        file2: { 
            path: "/second"
        },
        SubSubDir: {
            file3: {
                path: "/third"
            }
        }
    } 
};
const byPath = new Map();
function indexEntries(map, data) {
    for (const value of Object.values(data)) {
        if (value) {
            // Leaf or container?
            if (value.path) {
                map.set(value.path, value);
            } else {
                indexEntries(map, value);
            }
        }
    }
}
indexEntries(byPath, repAll);
const req = {};
for (const url of ["/first", "/second", "/third", "fourth"]) {
    req.url = url;
    console.log(req.url + ":", byPath.get(req.url));
}
.as-console-wrapper {
    max-height: 100% !important;
}

最新更新