node-文件操作

检查目录是否存在,创建目录

// node -v v12.*
const fs = require('fs');

// 查找目录 并判断是否存在目标文件夹
async function findDir(dirPath = '.', dirName) {
  try {
    const files = await fs.promises.readdir(dirPath, {
      encoding: 'utf8',
      withFileTypes: true,
    })
    return (
      files.length > 0 &&
      files.findIndex((item) => item.name === dirName && item.isDirectory()) > -1
    )
  } catch (err) {
    throw err
  }
}

// 创建目录
async function createDir(dirPath) {
  try {
    await fs.promises.mkdir(dirPath)
  } catch (err) {
    throw err
  }
}

// 检查是否存在目录 不存在则创建
async function findOrCreateDir() {
  await findDir('.', dir)
    .then((res) => {
      if (!res) {
        return createDir(dir)
      } else {
      }
    })
    .catch((e) => {
      console.error('error', e)
    })
}

// 检查是否存在目录 存在则清空
function delDir(path) {
  let files = []
  // if (fs.existsSync(path)) {
    files = fs.readdirSync(path, {
      withFileTypes: true
    })
    files.forEach((file) => {
      let curPath = `${path}/${file.name}`
      if (file.isDirectory()) {
        delDir(curPath) //递归删除文件夹
      } else {
        fs.unlinkSync(curPath) //删除文件
      }
    })
    fs.rmdirSync(path)
  // }
}
// 方法2
async function findOrCreateDir(path) {
    if (fs.existsSync(path)) {
        delDir(path)
    }
    await createDir(path)
}

循环删除空文件夹

// node -v v14.*
const fs = require('fs');
const path = require('path');


const originPath = path.resolve(__dirname, './source/_posts')

function resolveOriginPath(url) {
    return path.resolve(originPath, url)
}

function rmEmptyDir() {
    // 同步读取目录 过滤非文件夹目录及非空文件夹
    const files = fs.readdirSync(originPath, { withFileTypes: true })
                    .filter(file => {
                        if (file.isDirectory(resolveOriginPath(file.name))) {
                            return fs.readdirSync().length === 0
                        }
                        return false
                    })
    console.log(files)
    
    function rmDir(url) {
        fs.rmdir(url, err => {
            err && console.log('rm err: ', url, err)
        })
    }
    files.forEach(item => rmDir(resolveOriginPath(item.name)))
}