typescript中fs过滤出指定目录内包含指定扩展名称的所有文件的全路径
时间: 2024-02-20 22:57:53 浏览: 17
您好,以下是在TypeScript中实现过滤出指定目录内包含指定扩展名的所有文件的全路径的代码:
```typescript
import * as fs from 'fs';
import * as path from 'path';
function getFilesWithExt(dirPath: string, ext: string): string[] {
let fileArr: string[] = [];
const files = fs.readdirSync(dirPath);
for (const file of files) {
const filePath = path.join(dirPath, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
fileArr = fileArr.concat(getFilesWithExt(filePath, ext));
} else if (path.extname(file) === ext) {
fileArr.push(filePath);
}
}
return fileArr;
}
```
其中,`dirPath`为指定目录的路径,`ext`为指定的文件扩展名。这个函数会返回一个包含所有符合条件的文件路径的数组。您只需要调用这个函数并传入相应的参数即可。需要注意的是,该函数使用了同步的方式读取文件,如果需要异步读取可以使用`fs.readdir`和`fs.stat`。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)