current position:Home>node. JS traversal directory

node. JS traversal directory

2022-05-15 02:06:02thankseveryday

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

//  current path 
var root = path.join(__dirname)

let parentObj = {
    
    title: " Catalog ",
    children: []
}
//  call 
readDir(root, "", parentObj);
// console.log(JSON.stringify(parentObj, null, 2));
fs.writeFileSync(path.join(__dirname, "/ Catalog .json"), JSON.stringify(parentObj));
// console.log(path.join(__dirname + "/ Catalog .json"));

//  Directory traversal function 
function readDir(_path, level, parentObj) {
    
    //  Catalog depth 
    level = level + "——";
    //  Objects in the current directory 
    var curDirObjs = fs.readdirSync(_path);
    //  Traverse the total objects of the current directory 
    curDirObjs.forEach((_obj, index) => {
    
        //  Returns information about the current path object :? Catalog : file 
        var info = fs.statSync(_path + "/" + _obj)
        if (info.isDirectory()) {
    
            // ? Catalog 
            // console.log(level + _obj)
            let curObj = {
    
                title: _obj,
                children: []
            }
            parentObj.children.push(curObj)
            // dirNameArray.push(_obj);
            //  recursive 
            readDir(_path + "/" + _obj, level, curObj);
        } else {
    
            // ? file 
            // console.log("file: " + _obj)
        }
    })
}

copyright notice
author[thankseveryday],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/132/202205120527258745.html

Random recommended