因此,使用fs,我想读取某个目录(让我们称其为parent)中的所有内容,包括其他目录、其他目录中的文件以及parent中的文件。例如:Parent的路径:
/Parent/父级内部的一切
/Parent/index.js
/Parent/utils/utils.js
/Parent/Structures/thing.js我怎么才能得到所有这些呢?我尝试过fs.readdir和fs.readdirSync,但它只读取文件,不读取目录。
发布于 2021-03-30 04:25:42
如果您可以在自己的环境中访问Bash,则可以使用exec()执行find。
示例:
const { exec } = require("child_process");
exec("find /Parent/", (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});评论后更新:
使用递归函数递归获取某个目录下的所有文件:
const fs = require("fs")
const path = require("path")
const getAllFiles = function(dirPath, arrayOfFiles) {
files = fs.readdirSync(dirPath)
arrayOfFiles = arrayOfFiles || []
files.forEach(function(file) {
if (fs.statSync(dirPath + "/" + file).isDirectory()) {
arrayOfFiles = getAllFiles(dirPath + "/" + file, arrayOfFiles)
} else {
arrayOfFiles.push(path.join(__dirname, dirPath, "/", file))
}
})
return arrayOfFiles
}参考:https://coderrocketfuel.com/article/recursively-list-all-the-files-in-a-directory-using-node-js
https://stackoverflow.com/questions/66861077
复制相似问题