2014-02-28 68 views
0

我想使用節點js生成一個目錄樹到數組中。輸出將是:目錄樹的數組node.js

[ __Dirname [array of sub directories] ] 
["FolderA"[ ["SubFolderA",[]] ]], ["FolderB",[]] 

function readDir(dir){ 
    fs.readdir(dir, function(err, files){ 
     for(var i=0;i<files.length;i++){ 
     (function(j){ 
      fs.stat(files[j], function(err, stats){ 
      if(stats.isDirectory()){ 
       readDir(files[j]); 
      } 
      }); 
     } 
     } 
    }); 
} 

如果你知道一個更簡單的方法來做到這一點,請告訴我。我需要的是遞歸的目錄和所有子目錄的列表。

回答

2

以下代碼使用node-walker生成目錄樹對象

var path = require('path'); 
var util = require('util'); 
var walker = require('walker'); 

/* 
* To walk a directory and generate the tree object 
* 
* @param dest {string} the directory to start with. 
* @param cb {function} the callback function, cb(err, dirObj) 
* 
*/  
function readDir(dest, cb) { 
    var dirObj = {}; 
    var child, parts, obj; 

    walker(dest) 
    .on('dir', function(dir, stat) { 
     if (dir === dest) return; 

     child = dir.slice(dest.length, dir.length); 
     if (child.indexOf(path.sep) === 0) { 
     child = child.slice(1, child.length); 
     }; 

     parts = child.split(path.sep); 

     obj = dirObj; 

     for(var i=0;i<parts.length;i++) { 
     if (parts[i] !== '') { 
      if (obj[parts[i]] === undefined) { 
      obj[parts[i]] = {}; 
      }; 

      obj = obj[parts[i]]; 
     } 
     }; 
    }) 
    .on('error', function(err, entry, stat) { 
     cb(err, null); 
    }) 
    .on('end', function() { 
     cb(null, dirObj); 
    }) 
}; 

readDir(__dirname, function(err, dirObj) { 
    if (err) { 
    console.log(err); 
    } else { 
    // Handle the returned directory object 
    console.log(util.inspect(dirObj, {showHidden: true, depth: null})); 
    } 
});