【发布时间】:2015-10-20 09:19:00
【问题描述】:
假设我有这样的目录结构:
root
|_ .git
|_ .sass-cache
|_ css
| |_ scss
| | |_ modules
| | | |_ a-module.scss
| | | |_ ...
| | |_ partials
| | | |_ a-partial.scss
| | | |_ ...
| | |_ main.scss
| |_ main.css
| |_ main.css.map
...
|_ .bowerrc
|_ .gitignore
|_ app.js
|_ bower.json
|_ Gruntfile.js
|_ index.html
|_ package.json
|_ README.md
我正在使用以下代码生成此结构的 JSON,但它尚未保持我想要的顺序,如上所示,文件夹位于列表顶部(按字母顺序),文件位于位于列表底部(也按字母顺序)。
var fs = require('fs');
var path = require('path');
function getTree(filepath) {
filepath = path.normalize(filepath);
var stats = fs.lstatSync(filepath);
var info = {
path: filepath,
name: path.basename(filepath)
};
if (stats.isDirectory()) {
info.type = "directory";
info.children = fs.readdirSync(filepath).map(function(child) {
return getTree(path.join(filepath, child));
});
} else {
info.type = "file";
}
return info;
}
exports.getTree = getTree;
(修改自this答案)
这会以以下格式输出 JSON:
{
path: '/absolute/path/to/directory',
name: 'name-of-dir',
type: 'directory',
children:
[
{
path: '/absolute/path/to/file',
name: 'name-of-file',
type: 'file',
},
{
path: '/absolute/path/to/directory',
name: 'name-of-dir',
type: 'directory',
children:
[
{
...
}
]
}
]
}
我想知道如何最好地更改现有代码以对children 数组进行排序以复制目录结构顺序。检查应使用name 和type 属性来确定其在结果JSON 中的位置。
非常感谢
【问题讨论】:
-
创建一个平面列表?或者只是单独对每个 childNodes 进行排序?您可以递归调用
obj.nodes.sort。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
只是对孩子进行排序。
标签: javascript json node.js