nodejs递归删除文件,文件夹

import { unlink, rmdir, readdir, stat } from 'node:fs/promises'
import { join } from 'node:path'

const removeFile = (path) => {
  return new Promise((resolve, reject) => {
    checkStat(path)
      .then(isFile => {
        if (isFile) {
          return unlink(path)
        }
        return readdir(path)
      })
      .then(files => {
        if (Array.isArray(files)) {
          const removeFiles = files.map(file => removeFile(join(path, file)))
          return Promise.all(removeFiles)
        }
      })
      .then((files) => {
        if (Array.isArray(files)) {
          rmdir(path)
            .then(resolve, reject)
        } else {
          resolve()
        }
      })
  })
}

const checkStat = (path) => {
  return new Promise((resolve, reject) => {
    stat(path)
      .then(stat => {
        resolve(stat.isFile())
      })
      .catch(err => {
        reject(err)
      })
  })
}

export default removeFile

你可能感兴趣的:(nodejs,前端,javascript,node.js)