我试图以一种优雅的方式递归地列出其中的所有目录和文件。我想列出每个目录/子目录下的文件,以便于区分它们。并且目录路径必须由用户提供。我的工作如下,代码是完全可重现的,但是我不断得到空目录,并且文件被多次列出。在这里完成上市的更好的方法是什么?
//server.js
"use strict";
const fs = require("fs");
const rlp = require("readline");
const path = require("path");
const filesReadService = require("./filesReadService");
const handleFolders = require("./handleFolders");
// var basePath = "C:\\Users\\My Computer\\Videos\\Captures";
const rl = rlp.createInterface({
input: process.stdin,
output: process.stdout
});
function directoryInput() {
return new Promise((resolve, reject) => {
rl.question("Please enter a valid directory: ", input => resolve(input));
});
}
directoryInput().then(async userInput => {
rl.close();
let filesAndFolders = await handleFolders(userInput);
await filesReadService(userInput, filesAndFolders);
});
...
//handleFolders.js
const fs = require("fs");
const handleFolders = (directory, isRecursive) => {
return new Promise((resolve, reject) => {
fs.readdir(directory, (err, files) => {
if (err) {
reject(err);
return;
}
resolve(files);
});
});
};
module.exports = handleFolders;
...
//filesReadService.js
"use strict";
const fs = require("fs");
const path = require("path");
const handleFolders = require("./handleFolders");
const filesReadService = async (directoryPath, files) => {
let fullPath;
let obj = {};
var promises = files.map(file => {
fullPath = path.join(directoryPath, file);
return new Promise((resolve, reject) => {
fs.stat(fullPath, (err, stat) => {
if (err) {
reject(err);
return;
}
if (stat.isFile()) {
obj = {
file,
isFile: true
};
} else if (stat.isDirectory()) {
obj = {
file,
isFolder: true
};
}
resolve(obj);
});
});
});
Promise.all(promises).then(
values => {
console.log("The files in this directory:");
values
.filter(value => value.isFile)
.forEach(value => console.log(value.file));
console.log("\nThe folders in this directory:");
values
.filter(value => value.isFolder === true)
.forEach(async value => {
let folderPath = path.join(directoryPath, value.file);
let foldersAndFiles = await handleFolders(folderPath, true);
console.log(value.file, ":\t", foldersAndFiles);
await filesReadService(folderPath, foldersAndFiles);
});
},
err => {
console.log(err);
}
);
};
module.exports = filesReadService;
答案 0 :(得分:1)
const fs = require("fs"), path = require("path");
function recursivelyListDir(dir, callback) {
fs.readdirSync(dir).forEach(f => {
let dirPath = path.join(dir, f);
let isDirectory = fs.statSync(dirPath).isDirectory();
isDirectory
? recursivelyListDir(dirPath, callback)
: callback(path.join(dir, f));
});
}
// Function Usage.
recursivelyListDir(__dirname, function(filePath) {
const fileContents = fs.readFileSync(filePath, "utf8");
console.log(filePath);
});