preface

  1. What to do: What to do
  2. Why write: To play, to learnnode.jsFile system related apis; Tree structure this kind of thing is quite good, can use can build is really can
  3. What was used:fs.readdir(dir).fs.stat(dir).isFile().pathProcessing path, etc.
  4. Ideas:
    • Read the current folder (not a folder for another processing) to get an array of all files and directories under it;
    • Loop through the array and determine if it’s a folder or a file, which is pushed directly tochildFilesThe object has two properties:shortThe file name,fullFull file path)
    • For folder, the current folder is used firstkey, saved to the parent folderchildDirProperty and then self call pass current folder path
    • Each layer of folders contains three properties:dirFolder path,childFilesFile,childDirSubfolders, stored as object structures
    • Repeat the steps until you reach the bottom empty folder or the folder has only files
  • What the output looks likecomponents-dir-tree.json

{
    "dir": "D:\\node-test\\components"."childFiles": [{"short": "components-dir-tree.json"."full": "D:\\node-test\\components\\components-dir-tree.json"
        },
        {
            "short": "file.js"."full": "D:\\node-test\\components\\file.js"
        },
        {
            "short": "index.js"."full": "D:\\node-test\\components\\index.js"}]."childDir": {
        "no": null."test": {
            "dir": "D:\\node-test\\components\\test"."childFiles": []."childDir": {
                "aa": {
                    "dir": "D:\\node-test\\components\\test\\aa"."childFiles": [{"short": "bb.js"."full": "D:\\node-test\\components\\test\\aa\\bb.js"}]."childDir": {
                        "cc": null
                    }
                }
            }
        }
    }
}
Copy the code
  • Directory structure (Components only)

. | - components - index. Js - file. Js - components - dir - tree. Json / / the generated output file, the file tree object convenient view - notest
       -- aa
        -- cc
Copy the code
  • use

Format the output and write it to a JSON file so it looks obvious

components/index.js:
/** * init */
require('console-color-mr');  // Command line style
const fs = require('fs');
const path = require('path');
const { getDirTree, getDirName }  = require('./file.js');

const componentDir = path.resolve(__dirname, '/');
// console.log('componentDir: ', componentDir);

const ComponentInit = (function init() {
  console.log('______ init ______'.blueBG, '\n');
  let treeObj = getDirTree(componentDir);
  
  if (treeObj) {
    let outdir = `${__dirname}\ \${getDirName(componentDir)}-dir-tree.json`;
    
    // Write to the file
    fs.writeFile(outdir, JSON.stringify(treeObj, ' '.'\t'), 'utf8', (err) => {
      if (err) throw err;
      console.log('Directory tree has been output as a file save:${outdir}`.greenBG);
    });
  }
  returninit; }) ();module.exports = ComponentInit;
Copy the code
  • The main functiongetDirTree:

/components/file.js
const fs = require('fs');

@param {read path} dir * @returns Returns the file tree in the dir directory */
function getDirTree(dir) {
  let obj = {
    dir: dir, // The folder path
    childFiles: [], / / files
    childDir: {} / / subdirectory
  };
  let objStr = JSON.stringify(obj);
  if (isFile(dir)) return console.log(`${dir}: not folder '.redBG);
  
  // Read the directory
  let files = readDir(dir);
  if(! files.length)console.log(`${dir}: Folder is empty.redBG);
  
  // Walk through the file
  files.forEach(file= > {
    let tempdir = `${dir}\ \${file}`;
    if (isFile(tempdir)) {
      obj.childFiles.push({
        short: file, / / file name
        full: tempdir // Full path
      });
      
    } else {
      // console.log('tempdir: ',tempdir);
      let dirname = getDirName(tempdir);
      // In the current folder object childDir property (1), with the folder name as the key(2),
      // the value of (2) is an object consisting of the directory dir, childFiles, childDir subfolders, or nullobj.childDir[dirname] = getDirTree(tempdir); }});return JSON.stringify(obj) === objStr ? null : obj;
}
Copy the code
  • Tool functionreadDir/isFile

// Read the files and folders in the path
function readDir(dir) {
  return fs.readdirSync(dir, (err, files) => {
    if (err) throw err;
    // console.log(`${dir}, files: `.green, files);
    // if (! Files.length) console.log(' ${dir}: folder is empty '.redbg);
    returnfiles; })}// Determine if the specified path is a file
function isFile(dir) {
  return fs.statSync(dir).isFile();
}

// Get the directory name
function getDirName(dir) {
  let tempdir = dir.substr(dir.lastIndexOf('\ \') +1, dir.length);
  return tempdir;
}

// const components_out = readFile(path.resolve(__dirname, './components-dir-tree.json'));
// console.log('components-dir-tree: ', components_out);

// Read the files in the specified directory
function readFile(dir) {
  let result = fs.readFileSync(dir, 'utf-8');
  return (
    result 
    ? {
      dir: dir,
      result: result
    } 
    : null
  );
}

module.exports = {
  getDirTree,
  readDir,
  isFile,
  readFile
}
Copy the code

Node-test: Node-test: node-test: Node-test: Node-test

That’s it!