json - 使用 Node.js 将 URL/路径转换为 ​​Json

标签 json node.js function path

我最近构建了一个小 Node 程序,能够 console.log 精确路径的所有文件。 我从这个函数得到的结果看起来像这样:

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

现在我的问题是:如何设法将每个路径转换为 ​​JSON,以便我能够在单个 html 页面中显示电影文件夹的所有文件?

我想要这样的东西:

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

}

提前谢谢您。

顺便说一句,这是我的步行功能:

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

最佳答案

好的,我们开始吧:

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

这尚未经过测试,但也许它会给您一些如何做到这一点的想法。

关于json - 使用 Node.js 将 URL/路径转换为 ​​Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17533361/

相关文章:

json - 为什么 Amazon Redshift 不能解析这个有效的 JSON 字符串?

node.js - Sonarqube 未检测到使用 mocha 生成的 LCOV 报告

php - 如何使用externalInterface让Flash调用javascript来更新屏幕上的值?

Javascript 函数并返回 JSON

json - 如何在 JSON Postgres 数据类型列中搜索特定字符串?

javascript - 如何读取json数组中的值

node.js - 将 create-react-app 推送到 github node_modules 文件夹尚未复制

javascript - Node js azure SDK getBlobToStream 使用大量内存

python - 使用滚动 12 个月窗口将自定义函数应用于 Pandas Group

java - 如何使用 JSON 解析从任何 url 解析数据