2017-03-25 6 views
0

Ich schrieb eine Funktion, die Verzeichnisse durchläuft und analysiert Dateien in ihm, aber ich weiß nicht, wie zu erkennen, dass der gesamte Prozess getan wird (dass es alle Dateien in allen Verzeichnissen und Unterverzeichnissen analysiert) Ich kann dann etwas mit dem Ergebnis machen.Aktion nach Rekursion ist getan

Ich benutzte Rekursion, aber ich lerne immer noch und ich weiß, dass es nicht ganz richtig ist, also würde ich gerne um Hilfe bitten.

const path = require('path'); 
const fs = require('fs'); 
const _ = require('lodash'); 

let result = {}; 

const goThroughDirs = parentPath => { 
    const stat = fs.statSync(parentPath); 

    if (stat.isDirectory()) { 
     _.each(fs.readdirSync(parentPath), child => goThroughDirs(path.join(parentPath, child))); 
    } else { 
     analyseFile(parentPath) 
      .then(response => { 
       result = _.merge({}, result, response); 
      }); 
    } 
}; 

goThroughDirs(path.join(__dirname, 'rootDir')); 

Vielen Dank im Voraus für Hilfe.

Antwort

1

Da Sie bereits mit Versprechungen sind, ist es so einfach wie

function goThroughDirs(parentPath) { 
    const stat = fs.statSync(parentPath); 

    if (stat.isDirectory()) { 
     return Promise.all(_.map(fs.readdirSync(parentPath), child => 
//  ^^^^^^ ^^^^^^^^^^^ ^^^ 
      goThroughDirs(path.join(parentPath, child)) 
     )).then(responses => 
      _.merge({}, ...responses); 
     ); 
    } else { 
     return analyseFile(parentPath); 
//  ^^^^^^ 
    } 
} 

goThroughDirs(path.join(__dirname, 'rootDir')).then(result => { 
    // it's done 
    console.log(results); 
}); 
Verwandte Themen