持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第2天,点击查看活动详情
内容
有个想法,通过node.js的api获取一个文件夹下面的所有文件路径,肯定会涉及到递归调用
函数的大致逻辑
graph TD
Start --> 获取当前目录-->获取所有文件路径 --> 遇到文件夹重新遍历 --> 直到所有文件都遍历结束
function getAllFilepath() {
function pushFile(filepath, arr) {
const files = fs.readdirSync(filepath);
files.forEach((i) => {
const fileDir = path.join(filepath, i);
const fileSates = fs.statSync(fileDir);
const isDirectory = fileSates.isDirectory();
if (isDirectory) {
pushFile(fileDir, arr);
} else {
arr.push(fileDir);
}
});
}
const arr1 = [];
const filepath = path.resolve();
pushFile(filepath, arr1);
return arr1;
}
第二步,我们要实现如下的文件结构输出
|-- JS
|-- array.js
|-- ast.js
|-- class.js
|-- class.ts
|-- deepClone.js
|-- directoryList.md
|-- JSON.js
|-- mddir.js
|-- promise.js
|-- promiseT.js
|-- prototype.js
|-- reg.js
|-- test.js
|-- Algorithm
|-- 2Tree.js
|-- 3Sum.js
|-- arraySort.js
|-- doubleLinkLisk.js
|-- linkList.js
|-- mergeTwoList.js
可以看到,根文件夹缩进为0,第一级文件夹缩进为4,第三级为8,规律为2n,因此我们要给个index,每递归一次增加1,初始化为0
function getAllFilepath() {
function pushFile(filepath, arr, index) {
const files = fs.readdirSync(filepath);
files.forEach((i) => {
const fileDir = path.join(filepath, i);
const fileSates = fs.statSync(fileDir);
const isDirectory = fileSates.isDirectory();
arr.push({ file: i, index });
if (isDirectory) {
pushFile(fileDir, arr, index + 1);
} else {
// arr.push({ file: fileDir, index });
}
});
}
const filepath = path.resolve();
const arr1 = [{ file: path.basename(filepath), index: 0 }];
pushFile(filepath, arr1, 1);
return arr1;
}
const fileArr = getAllFilepath();
let text = "";
console.log(fileArr);
fileArr.forEach((i) => {
for (let j = 0; j < i.index; j++) {
text += ` `;
}
text += `|--${i.file}\n`;
});
最后我们需要创建一个文件写入对应的内容,就能输出文件格式的md文件
fs.writeFileSync("./test.md", text);
输出的内容如下
|--Test
|--directoryList.md
|--HTML
|--CSS
|--css.css
|--css.html
|--fingerPrint.css
|--fingerPrint.html
|--fingerPrint.scss
|--fly.html
|--debounce.html
|--index.html
|--react.html
|--Router
|--OriginalHash.html
|--OriginalHistory.html
|--SCO
|--alert.html
|--simple-web-worker-gh-pages
|--CODE_OF_CONDUCT.md
|--index.html
|--LICENSE
|--main.js
|--README.md
|--style.css
|--worker.js
总结
以后遇到类似需要遍历文件夹结构的可以采用类似的处理方法,我的输出数据是平铺的,也可以设计成文件夹类似的对象结构,可以满足更多的功能