web-dev-qa-db-fra.com

Convertir une structure de répertoires dans le système de fichiers en JSON avec Node.js

J'ai une structure de fichier comme celle-ci:

root
|_ fruits
|___ Apple
|______images
|________ Apple001.jpg
|________ Apple002.jpg
|_ animals
|___ cat
|______images
|________ cat001.jpg
|________ cat002.jpg

J'aimerais, à l'aide de Javascript et de Node.js, écouter ce répertoire racine et tous les sous-répertoires et créer un JSON qui reflète cette structure de répertoires. Chaque nœud contient le type, le nom, le chemin d'accès et les enfants:

data = [
  {
    type: "folder",
    name: "animals",
    path: "/animals",
    children: [
      {
        type: "folder",
        name: "cat",
        path: "/animals/cat",
        children: [
          {
            type: "folder",
            name: "images",
            path: "/animals/cat/images",
            children: [
              {
                type: "file",
                name: "cat001.jpg",
                path: "/animals/cat/images/cat001.jpg"
              }, {
                type: "file",
                name: "cat001.jpg",
                path: "/animals/cat/images/cat002.jpg"
              }
            ]
          }
        ]
      }
    ]
  }
];

Voici un JSON de café:

data = 
[
  type: "folder"
  name: "animals"
  path: "/animals"
  children  :
    [
      type: "folder"
      name: "cat"
      path: "/animals/cat"
      children:
        [
          type: "folder"
          name: "images"
          path: "/animals/cat/images"
          children: 
            [
              type: "file"
              name: "cat001.jpg"
              path: "/animals/cat/images/cat001.jpg"
            , 
              type: "file"
              name: "cat001.jpg"
              path: "/animals/cat/images/cat002.jpg"
            ]
        ]
    ]
]

comment obtenir ce format de données JSON dans les vues Django? (Python)

48
hagope

Voici un croquis. La gestion des erreurs reste un exercice pour le lecteur.

var fs = require('fs'),
    path = require('path')

function dirTree(filename) {
    var stats = fs.lstatSync(filename),
        info = {
            path: filename,
            name: path.basename(filename)
        };

    if (stats.isDirectory()) {
        info.type = "folder";
        info.children = fs.readdirSync(filename).map(function(child) {
            return dirTree(filename + '/' + child);
        });
    } else {
        // Assuming it's a file. In real life it could be a symlink or
        // something else!
        info.type = "file";
    }

    return info;
}

if (module.parent == undefined) {
    // node dirTree.js ~/foo/bar
    var util = require('util');
    console.log(util.inspect(dirTree(process.argv[2]), false, null));
}
62
Miikka

La réponse acceptée fonctionne, mais elle est synchrone et va nuire considérablement à vos performances, en particulier pour les arborescences de répertoires volumineuses.
Je vous encourage vivement à utiliser la solution asynchrone suivante: elle est à la fois plus rapide et non bloquante.
Basé sur la solution parallèle ici .

var fs = require('fs');
var path = require('path');

var diretoryTreeToObj = function(dir, done) {
    var results = [];

    fs.readdir(dir, function(err, list) {
        if (err)
            return done(err);

        var pending = list.length;

        if (!pending)
            return done(null, {name: path.basename(dir), type: 'folder', children: results});

        list.forEach(function(file) {
            file = path.resolve(dir, file);
            fs.stat(file, function(err, stat) {
                if (stat && stat.isDirectory()) {
                    diretoryTreeToObj(file, function(err, res) {
                        results.Push({
                            name: path.basename(file),
                            type: 'folder',
                            children: res
                        });
                        if (!--pending)
                            done(null, results);
                    });
                }
                else {
                    results.Push({
                        type: 'file',
                        name: path.basename(file)
                    });
                    if (!--pending)
                        done(null, results);
                }
            });
        });
    });
};

Exemple d'utilisation:

var dirTree = ('/path/to/dir');

diretoryTreeToObj(dirTree, function(err, res){
    if(err)
        console.error(err);

    console.log(JSON.stringify(res));
});
17
LifeQuery

il y a un module NPM pour cela

https://www.npmjs.com/package/directory-tree

Crée un objet représentant une arborescence de répertoires.

De:

photos
├── summer
│   └── june
│       └── windsurf.jpg
└── winter
    └── january
        ├── ski.png
        └── snowboard.jpg

À:

{
  "path": "",
  "name": "photos",
  "type": "directory",
  "children": [
    {
      "path": "summer",
      "name": "summer",
      "type": "directory",
      "children": [
        {
          "path": "summer/june",
          "name": "june",
          "type": "directory",
          "children": [
            {
              "path": "summer/june/windsurf.jpg",
              "name": "windsurf.jpg",
              "type": "file"
            }
          ]
        }
      ]
    },
    {
      "path": "winter",
      "name": "winter",
      "type": "directory",
      "children": [
        {
          "path": "winter/january",
          "name": "january",
          "type": "directory",
          "children": [
            {
              "path": "winter/january/ski.png",
              "name": "ski.png",
              "type": "file"
            },
            {
              "path": "winter/january/snowboard.jpg",
              "name": "snowboard.jpg",
              "type": "file"
            }
          ]
        }
      ]
    }
  ]
}

Usage

var tree = directoryTree('/some/path');

Et vous pouvez aussi filtrer par extensions:

var filteredTree = directoryTree('/some/path', ['.jpg', '.png']);
15
Asaf Katz

Mon exemple CS (w/express) basé sur la solution de Miika:

fs = require 'fs' #file system module
path = require 'path' # file path module

# returns json tree of directory structure
tree = (root) ->
    # clean trailing '/'(s)
    root = root.replace /\/+$/ , ""
    # extract tree ring if root exists
    if fs.existsSync root
        ring = fs.lstatSync root
    else
        return 'error: root does not exist'
    # type agnostic info
    info = 
        path: root
        name: path.basename(root)
    # dir   
    if ring.isDirectory()
        info.type = 'folder'
        # execute for each child and call tree recursively
        info.children = fs.readdirSync(root) .map (child) ->
            tree root + '/' + child
    # file
    else if ring.isFile()
        info.type = 'file'
    # link
    else if ring.isSymbolicLink()
        info.type = 'link'
    # other
    else
        info.type = 'unknown'
    # return tree 
    info

# error handling
handle = (e) ->
    return 'uncaught exception...'

exports.index = (req, res) ->
    try
        res.send tree './test/'
    catch e
        res.send handle e
3
fooling

Vous pouvez utiliser le code de ce projet mais vous devez l'adapter à vos besoins:

https://github.com/NHQ/Node-FileUtils/blob/master/src/file-utils.js#L511-L593

De:

a
|- b
|  |- c
|  |  |- c1.txt
|  |
|  |- b1.txt
|  |- b2.txt
|
|- d
|  |
|
|- a1.txt
|- a2.txt

À:

{
    b: {
        "b1.txt": "a/b/b1.txt",
        "b2.txt": "a/b/b2.txt",
        c: {
            "c1.txt": "a/b/c/c1.txt"
        }
    },
    d: {},
    "a2.txt": "a/a2.txt",
    "a1.txt": "a/a1.txt"
}

Faire:

new File ("a").list (function (error, files){
    //files...
});
1
Gabriel Llamas

Voici une solution asynchrone:

 function list(dir) {
   const walk = entry => {
     return new Promise((resolve, reject) => {
       fs.exists(entry, exists => {
         if (!exists) {
           return resolve({});
         }
         return resolve(new Promise((resolve, reject) => {
           fs.lstat(entry, (err, stats) => {
             if (err) {
               return reject(err);
             }
             if (!stats.isDirectory()) {
               return resolve({
                 // path: entry,
                 // type: 'file',
                 name: path.basename(entry),
                 time: stats.mtime,
                 size: stats.size
               });
             }
             resolve(new Promise((resolve, reject) => {
               fs.readdir(entry, (err, files) => {
                 if (err) {
                   return reject(err);
                 }
                 Promise.all(files.map(child => walk(path.join(entry, child)))).then(children => {
                   resolve({
                     // path: entry,
                     // type: 'folder',
                     name: path.basename(entry),
                     time: stats.mtime,
                     entries: children
                   });
                 }).catch(err => {
                   reject(err);
                 });
               });
             }));
           });
         }));
       });
     });
   }

   return walk(dir);
 }

Notez que lorsqu'un répertoire n'existe pas, un résultat vide est renvoyé plutôt qu'une erreur est générée.

Voici un exemple de résultat:

{
    "name": "root",
    "time": "2017-05-09T07:46:26.740Z",
    "entries": [
        {
            "name": "book.txt",
            "time": "2017-05-09T07:24:18.673Z",
            "size": 0
        },
        {
            "name": "cheatsheet-a5.pdf",
            "time": "2017-05-09T07:24:18.674Z",
            "size": 262380
        },
        {
            "name": "docs",
            "time": "2017-05-09T07:47:39.507Z",
            "entries": [
                {
                    "name": "README.md",
                    "time": "2017-05-08T10:02:09.651Z",
                    "size": 19229
                }
            ]
        }
    ]
}

qui sera:

root
|__ book.txt
|__ cheatsheet-a5.pdf
|__ docs
      |__ README.md
1
Sean C.

J'ai utilisé 'walk' lib dans ce cas, il récupère votre chemin racine, parcourt les fichiers et les répertoires de manière récursive et émet un événement répertoire/fichier avec toutes les informations dont vous avez besoin depuis un nœud, Vérifiez cette implémentation - >

const walk = require('walk');

class FsTree {

    constructor(){

    }

    /**
     * @param rootPath
     * @returns {Promise}
     */
    getFileSysTree(rootPath){
        return new Promise((resolve, reject)=>{

            const root = rootPath || __dirname; // if there's no rootPath use exec location
            const tree = [];
            const nodesMap = {};
            const walker  = walk.walk(root, { followLinks: false}); // filter doesn't work well

            function addNode(node, path){
                if ( node.name.indexOf('.') === 0 || path.indexOf('/.') >= 0){ // ignore hidden files
                    return;
                }
                var relativePath = path.replace(root,'');

                node.path = relativePath + '/' + node.name;
                nodesMap[node.path] = node;

                if ( relativePath.length === 0 ){ //is root
                    tree.Push(node);
                    return;
                }
                node.parentPath = node.path.substring(0,node.path.lastIndexOf('/'));
                const parent = nodesMap[node.parentPath];
                parent.children.Push(node);

            }

            walker.on('directory', (path, stats, next)=>{
                addNode({ name: stats.name, type:'dir',children:[]}, path);
                next();
            });

            walker.on('file', (path,stats,next)=>{
                addNode({name:stats.name, type:'file'},path);
                next();
            });

            walker.on('end',()=>{
                resolve(tree);
            });

            walker.on('errors',  (root, nodeStatsArray, next) => {
                reject(nodeStatsArray);
                next();
            });
        });

    }
}


const fsTreeFetcher = new FsTree();

fsTreeFetcher.getFileSysTree(__dirname).then((result)=>{
    console.log(result);
});
0
lironn

C'est le meilleur module pour cette tâche:

npm dree

Il y a beaucoup d'options personnalisées, le résultat pourrait être le suivant:

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

Même une chaîne pourrait être retournée, comme ceci:

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

Exemple:

const dree = require('dree');

const options = {
  stat: false,
  normalize: true,
  followLinks: true,
  size: true,
  depth: 5,
  exclude: [/dir_to_exclude/, /another_dir_to_exclude/ ],
  extensions: [ 'txt', 'jpg' ]
};

const tree = dree.scan('./folder', options);
0
EuberDeveloper