const fs = require('fs')
const path = require('path')
// 只需要改这两个路径就好,其他代码可以原封不动直接使用
const sourceDir = 'D:/demo111'
const targetDir = 'D:/demo222'
fs.readdir(sourceDir, (err, files) => {
if (err) throw err;
files.forEach(file => {
const sourcePath = path.join(sourceDir, file);
fs.stat(sourcePath, (err, stats) => {
if (err) throw err;
if (stats.isDirectory()) {
// 如果是子文件夹,递归复制子文件夹中的内容
const targetPath = path.join(targetDir, file);
fs.mkdir(targetPath, { recursive: true }, err => {
if (err) throw err;
copyFolder(sourcePath, targetPath);
});
} else {
// 如果是文件,直接复制文件
const targetPath = path.join(targetDir, file);
fs.copyFile(sourcePath, targetPath, err => {
if (err) throw err;
console.log(`${sourcePath} was copied to ${targetPath}`);
});
}
});
});
});
function copyFolder(sourcePath, targetPath) {
fs.readdir(sourcePath, (err, files) => {
if (err) throw err;
files.forEach(file => {
const sourceFile = path.join(sourcePath, file);
const targetFile = path.join(targetPath, file);
fs.stat(sourceFile, (err, stats) => {
if (err) throw err;
if (stats.isDirectory()) {
// 如果是子文件夹,递归复制子文件夹中的内容
fs.mkdir(targetFile, { recursive: true }, err => {
if (err) throw err;
copyFolder(sourceFile, targetFile);
});
} else {
// 如果是文件,直接复制文件
fs.copyFile(sourceFile, targetFile, err => {
if (err) throw err;
console.log(`${sourceFile} was copied to ${targetFile}`);
});
}
});
});
});
}
copyFolder(sourceDir, targetDir);
node脚本(把一个文件夹下的内容复制进另一个文件夹)
最新推荐文章于 2024-06-10 21:57:03 发布