1

I recently built a little node program able to console.log all the files of a precise path. The result I get from this function looks like this for instance :

/Volumes/TimeCapsule/movies/movie1
 movie1.mp4
/Volumes/TimeCapsule/movies/movie2
 movie2.mp4
/Volumes/TimeCapsule/movies/movie3
 movie3.mp4

Now my question is: how can I manage to convert each of this path to JSON so I could be able for instance to display all the files of the movie folder in a single html page ?

I would like to have something like this :

{ "Volumes": {
             "TimeCapsule": {
                            "Movies":{
                                    "Title": "Movie1"
                                    "Title": "Movie2"
                                    "Title": "Movie3"
                                   }
                            }
           }

}

Thank you in advance.

By the way here is my walk function :

var fs = require('fs');
var walk = function (currentPath) {
 console.log(currentPath);
 var files = fs.readdirSync(currentPath); //Returns array of filename in currenpath
 for (var i in files) {
   var currentFile = currentPath + '/' + files[i];
   var stats = fs.statSync(currentFile);
   if (stats.isFile()) {
   console.log(currentFile.replace(/^.*[\\\/]/, '')););
   }
  else if (stats.isDirectory()) {
         walk(currentFile);
       }
 }
};
4

2 回答 2

3

好的,我们开始:

var fs = require( "fs" );
function walk( path, arr ) {
    var ret = {};
    arr = Array.isArray( arr ) ? arr : [];

    fs.readdirSync( path ).forEach(function( item ) {
        var current = path + "/" + item;
        var stats = fs.statSync( current );
        if ( stats.isFile() ) {
            arr.push( current );
        } else if ( stats.isDirectory() ) {
            walk( current, arr );
        }
    });

    arr.forEach(function( item ) {
    var i, len;
        item.split( "/" ).reduce(function( obj, path, i, parts ) {
            if ( ( i + 1 ) === parts.length ) {
                obj.Title = path;
            } else {
                obj[ path ] = obj[ path ] || {};
                return obj[ path ];
            }
        }, ret);
    });

    return ret;
}

这没有经过测试,但也许它会给你一些关于如何做的想法。

于 2013-07-08T19:10:51.953 回答
0

这是我真正想要的,我什至添加了一个路径部分,这样我就可以访问每个文件的路径:

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

 function walk(path) {
     var stats = fs.lstatSync(mypath),
       info = {
        path: mypath,
        Title: path.basename(mypath)
    };

if (stats.isDirectory()) {
    info.type = "folder";
    info.children = fs.readdirSync(filename).map(function(child) {
        return walk(mypath + '/' + child);
    });
} else {
    info.type = "file";
}

return info;
}


console.log(walk('/Users/maximeheckel/Desktop'));

谢谢您的帮助。

于 2013-07-13T22:16:10.143 回答