Node.js学习笔记12:作业——读取文件夹内所有文件列表

结合前两节的内容:
写给小白的Node.js学习笔记10:fs模块读取文件列表
写给小白的Node.js学习笔记11:fs.stat判断文件类型
我们可以结合两种方法,读取文件夹内的全部文件列表。

思路如下:

  1. 通过fs.readdir方法读取路径,获取文件列表
  2. 对文件进行判断,如果是文件,则输出文件名,如果是文件夹,则读取该文件夹的路径,并对这个文件夹内部的文件再次进行判断
  3. 我们可以将上述方法封装到一个函数中,如果文件夹内还有文件夹,对内部文件夹再次讨厌函数即可(递归)
  4. 这里需要用到path.join方法,可以回顾《写给小白的node.js学习笔记8:path核心对象》
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const fs = require("fs");
const path = require("path");
let myPath = "/Application/MAMP/htdocs/nodejs/test/";

function myReadFile(tempPath) {
fs.readdir(tempPath, (err, files) => {
if(err) throw err;
files.forEach(file => {
let fPath = path.join(tempPath, file);
fs.stat(fPath, (err, stats) => {
if(err) throw err;
if(stats.isFile()){
console.log(file);
} else if (stats.isDirectory()){
myReadFile(fPath);
}
})
})
})
})

myReadFile(myPath);

输出结果如下:
输出结果