📅  最后修改于: 2023-12-03 15:08:43.698000             🧑  作者: Mango
在开发过程中,我们常常需要复制文件夹,例如将一个文件夹中的文件复制到另一个文件夹中。在 Node.js 中,可以使用 fs
模块来实现递归复制文件夹的功能。
实现递归复制文件夹的思路如下:
遍历源文件夹中的所有文件和子文件夹
复制文件夹时递归调用
复制文件时使用流进行读写
下面是递归复制文件夹的代码实现,其中 copyFolder
函数用于复制文件夹,copyFile
函数用于复制文件:
const fs = require('fs');
const path = require('path');
/**
* 复制文件夹
* @param {string} sourcePath 源文件夹路径
* @param {string} targetPath 目标文件夹路径
*/
function copyFolder(sourcePath, targetPath) {
// 如果源文件夹不存在,则返回
if (!fs.existsSync(sourcePath)) {
return;
}
// 如果目标文件夹不存在,则创建
if (!fs.existsSync(targetPath)) {
fs.mkdirSync(targetPath);
}
// 遍历源文件夹中的所有文件和子文件夹
const files = fs.readdirSync(sourcePath);
for (const file of files) {
const sourceFile = path.join(sourcePath, file);
const targetFile = path.join(targetPath, file);
const stats = fs.statSync(sourceFile);
if (stats.isDirectory()) {
// 如果是文件夹则递归复制
copyFolder(sourceFile, targetFile);
} else if (stats.isFile()) {
// 如果是文件则使用流进行读写
copyFile(sourceFile, targetFile);
}
}
}
/**
* 复制文件
* @param {string} sourceFile 源文件路径
* @param {string} targetFile 目标文件路径
*/
function copyFile(sourceFile, targetFile) {
const readStream = fs.createReadStream(sourceFile);
const writeStream = fs.createWriteStream(targetFile);
readStream.pipe(writeStream);
}
使用方法示例如下:
const sourcePath = './source-folder';
const targetPath = './target-folder';
copyFolder(sourcePath, targetPath);
上述代码将源文件夹中的文件复制到目标文件夹中。
至此,本篇文章介绍了如何在 Node.js 中递归复制文件夹。通过使用 fs
模块实现遍历文件夹、递归调用函数和使用流读写文件等功能,可以快速实现文件夹复制的需求。