nodejs 从 16.7.0版本开始,新加入了一个fs.cp()方法,可以复制目录(不管目标目录是否存在都可自动创建)。当需要复制目录时,需要将配置中的recursive属性设置为 true。
参考版
参考链接
let fs = require('fs');
let path = require("path");//工具模块,处理文件路径的小工具
/** 主要版本 */
let major = process.version.match(/v([0-9]*).([0-9]*)/)[1]
/** 特性版本 */
let minor = process.version.match(/v([0-9]*).([0-9]*)/)[2]
const tmpfiles = fs.readdirSync(path.resolve(__dirname, './tmp'))
tmpfiles.forEach(item => {
cpSync(path.resolve(__dirname, './common'), path.resolve(__dirname, `./tmp/${item}`))
})
/**
* 文件夹复制
* @param {string} source 源文件夹
* @param {string} destination 目标文件夹
*/
function cpSync(source, destination) {
// 判断node版本不是16.7.0以上的版本
// 则进入兼容处理
// 这样处理是因为16.7.0的版本支持了直接复制文件夹的操作
if (Number(major) < 16 || Number(major) == 16 && Number(minor) < 7) {
// 如果存在文件夹 先递归删除该文件夹
// if (fs.existsSync(destination)) fs.rmSync(destination, { recursive: true })
// 新建文件夹 递归新建
fs.mkdirSync(destination, { recursive: true });
// 读取源文件夹
let rd = fs.readdirSync(source)
rd.forEach(item => {
// 循环拼接源文件夹/文件全名称
let sourceFullName = source + "/" + item;
// 循环拼接目标文件夹/文件全名称
let destFullName = destination + "/" + item;
// 读取文件信息
let lstatRes = fs.lstatSync(sourceFullName)
// 是否是文件
if (lstatRes.isFile()) fs.copyFileSync(sourceFullName, destFullName);
// 是否是文件夹
if (lstatRes.isDirectory()) cpSync(sourceFullName, destFullName);
});
}
else fs.cpSync(source, destination, { force: true, recursive: true })
}
初学版
const fs = require('fs'),
path = require('path'),
// templatePath = path.join(__dirname, "./templates"), // 模板路径
tmpPath = path.resolve(__dirname, "./tmp"), // 模板路径
commonPath = path.resolve(__dirname, "./common")// 通用文件路径
// 1.读取文件 找到目标文件复制
const files = fs.readdirSync(commonPath)
const tmpfiles = fs.readdirSync(tmpPath)
// tmpfiles.forEach(item => {
// const tmpPath = path.resolve(__dirname, "./tmp/" + item)
// copyContent('', files)
// })
function copyContent(source, target) {
const files = fs.readdirSync(source)
files.forEach(item => {
const sourcePath = path.resolve(source, './' + item)
const targetPath = path.resolve(target, './' + item)
const data = fs.statSync(sourcePath)
if (data.isDirectory()) {
let checkDir = fs.existsSync(path.resolve(targetPath));
if (!checkDir) {
fs.mkdir(targetPath, { recursive: true }, err => { })
}
copyContent(sourcePath, targetPath)
return
} else {
const rs = fs.createReadStream(sourcePath)
const ws = fs.createWriteStream(targetPath)
// 绑定 data 事件
rs.on('data', (chunk) => {
ws.write(chunk)
})
}
})
}
copyContent(path.resolve(__dirname, "./common"), path.resolve(__dirname, "./tmp/tmp1"))