在node.js中如何递归遍历指定目录?
时间: 2023-11-16 18:21:55 浏览: 61
在node.js中递归遍历指定目录可以使用`fs`模块中的`readdirSync`和`statSync`方法实现,具体步骤如下:
1. 使用`readdirSync`方法获取指定目录下所有文件和子目录的名称数组。
2. 遍历名称数组,使用`statSync`方法获取每个文件和目录的详细信息,判断是否是目录。
3. 如果是目录,则递归调用当前方法,传入子目录路径进行遍历。
4. 如果是文件,则可以进行其他操作,比如读取文件内容等。
下面是一个示例代码:
```javascript
const fs = require('fs');
const path = require('path');
function traverseDir(dirPath) {
const files = fs.readdirSync(dirPath);
for (let i = 0; i < files.length; i++) {
const filePath = path.join(dirPath, files[i]);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
// 递归遍历子目录
traverseDir(filePath);
} else {
// 处理文件
console.log(filePath);
}
}
}
// 示例:遍历当前目录下的所有文件和子目录
traverseDir('.');
```
需要注意的是,以上代码仅用于演示递归遍历目录的基本思路,实际应用中还需要考虑一些细节问题,比如异常处理、异步遍历等。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)