且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Node.js 将文件系统中的目录结构转换为 JSON

更新时间:2023-02-25 15:27:03

这是一个草图.错误处理留给读者作为练习.

Here's a sketch. Error handling is left as an exercise for the reader.

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