问题描述
xlsx-modules
├── 0-99
├── 100-199
│ ├── dr111.xls
│ ├── DR115.xls
│ └── DR130.xls
├── 200-299
└── 300-399
└── DR303.xlsx
我尝试获取文件名包含代码的文件的路径。例如,代码为 111 的搜索应返回 xlxs-modules/100-199/dr111.xls
我搜索了信息或示例但没有成功,可以指导我如何实现这一目标。问候和感谢
解决方法
我必须通过实施来解决这个问题
import * as fs from "fs";
import { join } from "path";
export function getFiles() {
const files: string[] = [];
function collectFiles(directory: string) {
const fileList = fs.readdirSync(directory);
for (const fileListElement of fileList) {
const absolutePath = join(directory,fileListElement);
if (fs.statSync(absolutePath).isDirectory()) {
collectFiles(absolutePath);
} else {
files.push(absolutePath);
}
}
}
collectFiles(`${process.cwd()}/xlsx-modules`);
return files;
}
这个函数递归地获取目录中文件的列表,我得到这样的结果
[
"/home/a123/projects/xlsx-modules/100-199/dr115.xls","/home/a123/projects/xlsx-modules/100-199/DR130.xls","/home/a123/projects/xlsx-modules/100-199/DR111.xls","/home/a123/projects/xlsx-modules/300-399/DR303.xlsx"
]
我使用这个函数来获取文件路径,然后做一些字符串匹配
getModuleBy(code: string) {
const files: string[] = getFiles();
const file = files.find((file) => file.includes(code));
if (!file) {
throw new NotFoundException(`Module with code ${code} not found`);
}
return file;
}