检查目录是否存在,创建目录
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 = []
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)
}
async function findOrCreateDir(path) {
if (fs.existsSync(path)) {
delDir(path)
}
await createDir(path)
}
循环删除空文件夹
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)))
}