1. Traverse all files in the corresponding folder in the input parameter and return the complete path of the corresponding file

const fs = require("fs")
const path = require("path")

function travel(basePath, callback) {
  fs
    .readdirSync(basePath)
    .forEach((file) = > {
      let filePath = path.join(basePath, file)
      if (fs.statSync(filePath).isDirectory()) {
        // If it is a folder, the recursion continues
        travel(filePath, callback)
      } else {
        callback(filePath)
      }
    })
}

/ / use
let basePath = './server' // Can be an absolute path starting with the disk name: 'F:/server'

travel(basePath, function (filePath) {
  console.log(filePath)
})
Copy the code

2. Create directories and files based on the input path

const fs = require("fs")
const path = require("path")
// Generate a fully recognized path
const toResolvePath = (. file) = >path.resolve(process.cwd(), ... file);// Create directory
const dirCreate = (targetPath, cb) = > {
    if (fs.existsSync(targetPath)) {
        cb()
    } else {
        dirCreate(path.dirname(targetPath), () = > {
            fs.mkdirSync(targetPath)
            cb()
        })
    }
}
const generateDirectoryCreate = async (dirPath) => {
    return new Promise((resolve, reject) = > {
        dirCreate(dirPath, resolve)
    })
}

// Create a file
const generateFileCreate = async (filePath, content) => {
    return new Promise((resolve, reject) = > {
        fs.writeFile(filePath, content, 'utf8'.err= > {
            if (err) {
                console.log(err.message);
                reject(err)
            } else {
                resolve()
            }
        })
    })
}

/ / use
const basePath = './aaa/bbb'
const resolvedPath = toResolvePath(basePath);
// Create a directory according to path
generateDirectoryCreate(resolvedPath);
// Create a file according to path
generateFileCreate(toResolvePath(basePath, 'index.js'), 'aaabbb\ncccddd');
Copy the code