Hier ist eine rekursive Lösung. Sie können es testen, speichern Sie es in einer Datei, führen Sie node yourfile.js /the/path/to/traverse
.
const fs = require('fs');
const path = require('path');
const util = require('util');
const traverse = function(dir, result = []) {
// list files in directory and loop through
fs.readdirSync(dir).forEach((file) => {
// builds full path of file
const fPath = path.resolve(dir, file);
// prepare stats obj
const fileStats = { file, path: fPath };
// is the file a directory ?
// if yes, traverse it also, if no just add it to the result
if (fs.statSync(fPath).isDirectory()) {
fileStats.type = 'dir';
fileStats.files = [];
result.push(fileStats);
return traverse(fPath, fileStats.files)
}
fileStats.type = 'file';
result.push(fileStats);
});
return result;
};
console.log(util.inspect(traverse(process.argv[2]), false, null));
Ausgabe sieht wie folgt aus:
[ { file: 'index.js',
path: '/stackoverflow/test-class/index.js',
type: 'file' },
{ file: 'message.js',
path: '/stackoverflow/test-class/message.js',
type: 'file' },
{ file: 'somefolder',
path: '/stackoverflow/test-class/somefolder',
type: 'dir',
files:
[ { file: 'somefile.js',
path: '/stackoverflow/test-class/somefolder/somefile.js',
type: 'file' } ] },
{ file: 'test',
path: '/stackoverflow/test-class/test',
type: 'file' },
{ file: 'test.c',
path: '/stackoverflow/test-class/test.c',
type: 'file' } ]
Bitte zeigen Sie uns, was Sie versucht haben, so weit –
_ „Und auch ein Verzeichnis der Datei“ _ Sie dies bereits haben, da sonst die fs-Methode verwendet wouldn Ich weiß nicht, welches Verzeichnis Sie lesen wollten. Wenn Sie den Pfad für jedes Unterverzeichnis meinen, dann verketten Sie einfach jeden Unterverzeichnisnamen mit dem Pfad, wenn Sie tiefer gehen. Aber ohne Ihren Code zu sehen, können wir Ihnen nicht genau sagen, wie Sie Ihren Code reparieren können. –