51 lines
1.2 KiB
JavaScript
51 lines
1.2 KiB
JavaScript
|
const fs = require('fs').promises
|
||
|
const path = require('path')
|
||
|
|
||
|
// 复制文件夹到指定目录
|
||
|
async function copyDirectory (source, destination) {
|
||
|
const entries = await fs.readdir(source, { withFileTypes: true });
|
||
|
await fs.mkdir(destination, { recursive: true });
|
||
|
for (let entry of entries) {
|
||
|
const srcPath = path.join(source, entry.name);
|
||
|
const destPath = path.join(destination, entry.name);
|
||
|
|
||
|
if (entry.isDirectory()) {
|
||
|
await copyDirectory(srcPath, destPath);
|
||
|
} else {
|
||
|
await fs.copyFile(srcPath, destPath);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// 删除文件夹
|
||
|
async function deleteDirectory (dir) {
|
||
|
const isExist = await fileExists(dir)
|
||
|
if (!isExist) {
|
||
|
return true
|
||
|
}
|
||
|
const entries = await fs.readdir(dir, { withFileTypes: true })
|
||
|
for (let entry of entries) {
|
||
|
const fullPath = path.join(dir, entry.name)
|
||
|
if (entry.isDirectory()) {
|
||
|
await deleteDirectory(fullPath)
|
||
|
} else {
|
||
|
await fs.unlink(fullPath)
|
||
|
}
|
||
|
}
|
||
|
await fs.rmdir(dir)
|
||
|
}
|
||
|
|
||
|
// 判断文件是否存在
|
||
|
async function fileExists(filePath) {
|
||
|
try {
|
||
|
await fs.access(filePath);
|
||
|
return true; // 文件存在
|
||
|
} catch {
|
||
|
return false; // 文件不存在
|
||
|
}
|
||
|
}
|
||
|
|
||
|
module.exports = {
|
||
|
copyDirectory,
|
||
|
deleteDirectory
|
||
|
}
|