一、复制文件或文件夹
1.同步复制
const fs = require('fs'); //文件模块
const path = require('path'); //系统路径模块
/**
* 同步复制文件或文件夹
* @param {String} fromPath 源始路径,参数可以是文件或文件夹
* @param {String} toPath 目标路径,参数可以是文件或文件夹
*/
function copyFileSync(fromPath, toPath, cb) {
try {
fs.accessSync(toPath);
} catch (err) {
fs.mkdirSync(toPath)
}
const filenames = fs.readdirSync(fromPath);
filenames.forEach((filename) => {
const newFromPath = path.join(fromPath, filename);
const newToPath = path.join(toPath, filename);
const stat = fs.statSync(newFromPath);
if (stat.isFile()) {
fs.copyFileSync(newFromPath, newToPath);
}
if (stat.isDirectory()) {
copyFileSync(newFromPath, newToPath, cb);
}
})
}
应用示例:复制文件夹a到b
const path = require('path'); //系统路径模块
const pathA = path.join(__dirname, './a');
const pathB = path.join(__dirname, './b');
copyFileSync(pathA, pathB);
2.异步复制
/**
* 异步复制文件或文件夹
* @param {*} fromPath 源始路径,参数可以是文件或文件夹
* @param {*} toPath 目标路径,参数可以是文件或文件夹
*/
function copyFile(fromPath, toPath) {
return new Promise((resolve, reject) => {
fs.access(fromPath, err => {
if (err) reject(err)
fs.stat(fromPath, (err, stats) => {
//如果是文件
if (stats.isFile()) {
fs.copyFile(fromPath, toPath, (err) => {
err ? reject(err) : resolve();
});
} else {
fs.access(toPath, err => {
// 如果不存在则创建
new Promise((resv, rejt) => {
err ? fs.mkdir(toPath, err => (err ? rejt(err) : resv())) :

本文介绍了如何使用Node.js进行文件同步复制、异步复制,删除文件和文件夹,以及同步替换文件内容的方法。涵盖了从基本操作到高级技巧,适合开发人员快速上手文件处理任务。
最低0.47元/天 解锁文章
727





