node实现文件夹的拷贝
执行方式:(文件夹必须使用绝对路径)
node 执行文件 源文件夹 目标文件夹
const fs = require('fs');
const path = require('path');
//获取复制粘贴的文件夹
const srcDir = process.argv[2];
const desDir = process.argv[3];
function copyDir(srcDir, desDir) {
fs.readdir(srcDir, { withFileTypes: true }, (err, files) => {
for (const file of files) {
//判断是否为文件夹
if (file.isDirectory()) {
const dirS = path.resolve(srcDir, file.name);
const dirD = path.resolve(desDir, file.name);
//判断是否存在dirD文件夹
if (!fs.existsSync(dirD)) {
fs.mkdir(dirD, (err) => {
if (err) console.log(err);
});
}
copyDir(dirS, dirD);
} else {
const srcFile = path.resolve(srcDir, file.name);
const desFile = path.resolve(desDir, file.name);
fs.copyFileSync(srcFile, desFile);
console.log(file.name + ' 拷贝成功');
}
}
})
}
copyDir(srcDir, desDir);