我正试图从文件系统返回一个文件结构,以";目录列表";如果在Web服务器中找不到index.html文件。
我有一个遍历目录并将级别添加到数组的函数
function getAllFiles(dirPath){
var accPath = [];
fs.readdirSync(dirPath).forEach(function(file) {
let filepath = path.join(dirPath , file);
let stat= fs.statSync(filepath);
if (stat.isDirectory()) {
getAllFiles(filepath);
} else {
accPath.push(filepath);
}
});
accPath.forEach(elm => {
// to check that I have traversed directory
console.log(elm);
})
return accPath; // returning the directory array
}
我这样使用它:
var dirStructure = [];
dirStructure = getAllFiles(filePath);
console.log("noOfFiles "+dirStructure.length);
dirStructure.forEach(lmnt => {
console.log(lmnt);
})
结果是";getAllFiles"列出
publiccssbootstrap.min.css
publicjsbootstrap.min.js
publicjsjquery-3.3.1.slim.min.js
publicjspopper.min.js
publicindex2.html
但我只得到一个元素;dirStructure";阵列
"noOfFiles 1"
publicindex2.html
正如我在评论中所说,您永远不会使用递归调用
我建议像accPath.push(...getAllFiles(filepath))
一样将其推入accPath
const fs = require('fs')
const path = require('path')
function getAllFiles(dirPath) {
const accPath = [];
fs.readdirSync(dirPath).forEach(file => {
const filepath = path.join(dirPath, file);
const stat = fs.statSync(filepath);
if (stat.isDirectory()) {
// you have to use the data returned from getAllFiles
accPath.push(...getAllFiles(filepath));
} else {
accPath.push(filepath);
}
});
return accPath;
}