preface

Here’s the first version:

  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

Improvement:

  • Add directory filtering rules (regular expressions). Filter (I) or just get (c) based on the regular expression; The default filter["/node_modules|.git/i"]
  • Filtered regular expression format:["regx"], such as["/node_modules|.git/i"],["/components/"]
  • Add structure tree output, similarlytreeortreer”, similar to the project structure seen throughout the Nuggets
  • throughnpm scriptsUsing different commands, adding different parameters,process.envPass variables (filter typesi/c, a regular)

Source code can be stamped here: github address

I. Output content

  • components-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
  • components-dir-tree.json: output

"output": "D: \ \ node - test \ n └ ─ components \ n ├ ─ components - dir - tree1. Json \ n ├ ─ file. 2. Js \ n ├ ─ file. The bakeup. Js \ n ├ ─ file. The js \ n ├ ─ Index. Js \ n ├ ─ the js \ n ├ ─ node - test - dir - tree. Json \ n ├ ─ the run - sh. Js \ n ├ ─ test \ n └ ─ aa \ n ├ ─ bb. Js \ n └ ─ cc \ n └ ─ timeFormat.js\n"
Copy the code
D:\node-test ├─ Components ├─ Component-dir-Tree. json ├─ file2..js ├ ─ file. Bakeup. Js ├ ─ file. The js ├ ─ index. The js ├ ─ the js ├ ─ node - test - dir - tree. Json ├ ─ the run - sh. Js ├ ─ test └ ─ aa ├ ─ bb. Js └ ─ ├─ ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ Scripts └ ─ generateComponent. Js └ ─ sh └ ─ sh1. JsCopy the code

Main functiongetDirTree:

//components/file.2.js:
const fs = require('fs');
I: ignore/ c: contain
const type = process.env.getDirTreeType;
/ / regular expression ["/node_modules. | git/I "]
let reg = process.env.getDirTreeReg;

// Regular expression conversion
let modifier = reg.substring(reg.lastIndexOf('/') +1, reg.lastIndexOf('] ')) || 'i'; / / modifier
reg = reg.substring(reg.indexOf('/') +1, reg.lastIndexOf('/')); // Intercepts the expression model

reg = new RegExp(reg, modifier); // Generate a regular expression

let firstRun = true; // getDirTree is executed for the first time
let output = ' '; // Generates a directory structure string
@param {read path} dir * @returns Returns the file tree in the dir directory */
function getDirTree(dir) {
  let obj = {
    dir: dir,
    childFiles: [].childDir: {}};let objStr = JSON.stringify(obj);
  if (firstRun && isFile(dir)) return console.log(`${dir}: not folder '.redBG);

  let files = readDir(dir);
  
  if (firstRun) {
    output=`${dir}\n`;
    // Filter files and folders based on the re
    files = filesFilter(files);
    // List of files and folders after filtering
    log('files: ', files);
  }

  firstRun = false;

  // Walk through the file
  files.forEach((file, index) = > {
    let tempdir = `${dir}\ \${file}`;
    let dirname = getDirName(tempdir);
    / / dir depth
    let dirDeep = new Array(tempdir.split('\ \').length - 2).fill(0);
    
    dirDeep = dirDeep.reduce((acc,cur) = > 
      acc = (dirDeep.length > 1 ? ' ' : ' ') + acc, 
      index === files.length - 1 ? '└─ ' : '├─ '
    );
    
    output += `${dirDeep}${dirname}\n`;
    obj.output = output;

    log('output: \n'.green, output);

    if (isFile(tempdir)) {
      obj.childFiles.push({
        short: file, / / file name
        full: tempdir // Full path
      });
      
    } else {
      // console.log('tempdir: ',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

Third, utility functions

  • Directory filtering:

// Filter files and folders based on the re
function filesFilter(files) {
  switch (type) {
    case 'i': // Filter out ignored files and folders
      files = files.filter(item= >! reg.test(item));break;
    case 'c': / / contains
      files = files.filter(item= > reg.test(item));
      break;
    default:
      break;
  }
  return files;
}

Copy the code
  • otherreadDir/isFile/getDirNameEtc.

// 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

Fourth, call

  • package.json:

{..."scripts": {
    "gettreer": "node index.js --i"."gettreer:i": "node index.js --i"."gettreer:c": "node index.js --c",},... }Copy the code
  • The function body

// components/index.js
// Get directory tree initialization
function getDirTreeInit() {
  program
    .version('0.0.1')
    .option('-i --i [i]'.'ignore file or files')
    .option('-c --c [c]'.'contain file or files')
    .parse(process.argv);
  
  / / to accept command line arguments NPM run gettreer: I ["/node_modules. | git/I "]
  let reg = (typeof program.i === 'string' && program.i) 
    || (typeof program.c === 'string' && program.c)  
    || '[/node_modules|.git/i]';
  process.env.getDirTreeType = program.c ? 'c' : 'i'; // Ignore the filter
  process.env.getDirTreeReg = reg; // Regular expressions

  const { getDirTree, getDirName } = ' ' 
    ? require('./file.js') // Last version
    : require('./file.2.js'); // This is an improved version

  let treeObj = getDirTree(componentDir);
  // console.log('treeObj: ',treeObj);

  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); }); }}Copy the code

That’s it!