admin管理员组

文章数量:1336196

I am trying to generate a directory tree into an array using node js. Output would be:

[ __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]);
            }
          });
        }
      }
   });
}

If you know an easier way to do this please inform me. All I need is a list of directories and all their sub directories recursively.

I am trying to generate a directory tree into an array using node js. Output would be:

[ __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]);
            }
          });
        }
      }
   });
}

If you know an easier way to do this please inform me. All I need is a list of directories and all their sub directories recursively.

Share edited Feb 28, 2014 at 5:58 mikemil 1,26111 silver badges22 bronze badges asked Feb 28, 2014 at 5:23 user1348044user1348044
Add a ment  | 

2 Answers 2

Reset to default 3

The following code uses node-walker to generate the directory tree object.

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}));
  }
});

You can try this module:

npm dree

There are lots of custom options, a result could be this:

{
  "name": "sample",
  "path": "D:/Github/dree/test/sample",
  "relativePath": ".",
  "type": "directory",
  "size": "1.81 MB",
  "children": [
    {
      "name": "backend",
      "path": "D:/Github/dree/test/sample/backend",
      "relativePath": "backend",
      "type": "directory",
      "size": "1.79 MB",
      "children": [
        {
          "name": "firebase.json",
          "path": "D:/Github/dree/test/sample/backend/firebase.json",
          "relativePath": "backend/firebase.json",
          "type": "file",
          "extension": "json",
          "size": "29 B"
        }, 
        {
          "name": "server",
          "path": "D:/Github/dree/test/sample/backend/server",
          "relativePath": "backend/server",
          "type": "directory",
          "size": "1.79 MB",
          "children": [
            {
              "name": "server.js",
              "path": "D:/Github/dree/test/sample/backend/server/server.js",
              "relativePath": "backend/server/server.js",
              "type": "file",
              "extension": "js",
              "size": "1.81 MB"
            }
          ]
        }
      ]
    }
  ]
}

Even a string could be returned, like this:

sample
 └─> backend
     ├── firebase.json
     ├── hello.txt
     └─> server
         └── server.js

You can use it to get an object structure of the directory tree and then convert it to an array.

This codesandbox has the solution (see the solution.js file):

本文标签: javascriptArray of directory tree nodejsStack Overflow