目录树node.js的数组

时间:2014-02-28 05:23:19

标签: javascript node.js directory

我正在尝试使用节点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]);
            }
          });
        }
      }
   });
}

如果您知道更简单的方法,请通知我。我只需要递归地列出目录及其所有子目录。

3 个答案:

答案 0 :(得分: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}));
  }
});

答案 1 :(得分:2)

您可以尝试以下模块:

npm dree

有很多自定义选项,结果可能是这样的:

{
  "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"
            }
          ]
        }
      ]
    }
  ]
}

甚至可以返回一个字符串,如下所示:

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

您可以使用它来获取目录树的对象结构,然后将其转换为数组。

此codeandbox具有解决方案(请参阅solution.js文件):

Edit Setup Basic Node.js Server

答案 2 :(得分:0)

您可以使用此模块:

npm dree

有很多自定义选项,结果可能是这样的:

{
  "name": "sample",
  "path": "D:/Github/dree/test/sample",
  "relativePath": ".",
  "type": "directory",
  "size": "1.79 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.ts",
              "path": "D:/Github/dree/test/sample/backend/server/server.ts",
              "relativePath": "backend/server/server.ts",
              "type": "file",
              "extension": "ts",
              "size": "1.79 MB"
            }
          ]
        }
      ]
    }
  ]
}

甚至可以返回一个字符串,如下所示:

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

您可以使用它来获取目录树的对象结构,然后将其转换为数组。

此codeandbox具有解决方案(请参阅solution.js文件):

Edit Setup Basic Node.js Server