是否有一种更简单的方法来复制文件夹及其所有内容,而无需手动执行一系列的fs。readir, fs。readfile, fs。writefile递归?
我只是想知道我是否错过了一个函数,理想情况下是这样工作的:
fs.copy("/path/to/source/folder", "/path/to/destination/folder");
关于这个历史问题。注意fs。Cp和fs。cpSync可以递归复制文件夹,在Node v16+中可用
是否有一种更简单的方法来复制文件夹及其所有内容,而无需手动执行一系列的fs。readir, fs。readfile, fs。writefile递归?
我只是想知道我是否错过了一个函数,理想情况下是这样工作的:
fs.copy("/path/to/source/folder", "/path/to/destination/folder");
关于这个历史问题。注意fs。Cp和fs。cpSync可以递归复制文件夹,在Node v16+中可用
当前回答
我尝试了fs-extra和copy-dir来递归地复制文件夹。但我希望它能
正常工作(copy-dir抛出一个不合理的错误) 在过滤器中提供两个参数:filepath和filetype (fs-extra不告诉文件类型) 有从目录到子目录的检查和从目录到文件的检查吗
所以我自己写了:
// Node.js module for Node.js 8.6+
var path = require("path");
var fs = require("fs");
function copyDirSync(src, dest, options) {
var srcPath = path.resolve(src);
var destPath = path.resolve(dest);
if(path.relative(srcPath, destPath).charAt(0) != ".")
throw new Error("dest path must be out of src path");
var settings = Object.assign(Object.create(copyDirSync.options), options);
copyDirSync0(srcPath, destPath, settings);
function copyDirSync0(srcPath, destPath, settings) {
var files = fs.readdirSync(srcPath);
if (!fs.existsSync(destPath)) {
fs.mkdirSync(destPath);
}else if(!fs.lstatSync(destPath).isDirectory()) {
if(settings.overwrite)
throw new Error(`Cannot overwrite non-directory '${destPath}' with directory '${srcPath}'.`);
return;
}
files.forEach(function(filename) {
var childSrcPath = path.join(srcPath, filename);
var childDestPath = path.join(destPath, filename);
var type = fs.lstatSync(childSrcPath).isDirectory() ? "directory" : "file";
if(!settings.filter(childSrcPath, type))
return;
if (type == "directory") {
copyDirSync0(childSrcPath, childDestPath, settings);
} else {
fs.copyFileSync(childSrcPath, childDestPath, settings.overwrite ? 0 : fs.constants.COPYFILE_EXCL);
if(!settings.preserveFileDate)
fs.futimesSync(childDestPath, Date.now(), Date.now());
}
});
}
}
copyDirSync.options = {
overwrite: true,
preserveFileDate: true,
filter: function(filepath, type) {
return true;
}
};
还有一个类似的函数mkdirs,它是mkdirp的替代:
function mkdirsSync(dest) {
var destPath = path.resolve(dest);
mkdirsSync0(destPath);
function mkdirsSync0(destPath) {
var parentPath = path.dirname(destPath);
if(parentPath == destPath)
throw new Error(`cannot mkdir ${destPath}, invalid root`);
if (!fs.existsSync(destPath)) {
mkdirsSync0(parentPath);
fs.mkdirSync(destPath);
}else if(!fs.lstatSync(destPath).isDirectory()) {
throw new Error(`cannot mkdir ${destPath}, a file already exists there`);
}
}
}
其他回答
我是这样做的:
let fs = require('fs');
let path = require('path');
然后:
let filePath = // Your file path
let fileList = []
var walkSync = function(filePath, filelist)
{
let files = fs.readdirSync(filePath);
filelist = filelist || [];
files.forEach(function(file)
{
if (fs.statSync(path.join(filePath, file)).isDirectory())
{
filelist = walkSync(path.join(filePath, file), filelist);
}
else
{
filelist.push(path.join(filePath, file));
}
});
// Ignore hidden files
filelist = filelist.filter(item => !(/(^|\/)\.[^\/\.]/g).test(item));
return filelist;
};
然后调用该方法:
This.walkSync(filePath, fileList)
这段代码可以很好地工作,递归地将任何文件夹复制到任何位置。但它只适用于Windows。
var child = require("child_process");
function copySync(from, to){
from = from.replace(/\//gim, "\\");
to = to.replace(/\//gim, "\\");
child.exec("xcopy /y /q \"" + from + "\\*\" \"" + to + "\\\"");
}
它非常适合我的基于文本的游戏去创造新玩家。
fs-extra模块工作起来很有魅力。
安装fs-extra:
$ npm install fs-extra
下面是将源目录复制到目标目录的程序。
// Include the fs-extra package
var fs = require("fs-extra");
var source = 'folderA'
var destination = 'folderB'
// Copy the source folder to the destination
fs.copy(source, destination, function (err) {
if (err){
console.log('An error occurred while copying the folder.')
return console.error(err)
}
console.log('Copy completed!')
});
参考文献
fs-extra: https://www.npmjs.com/package/fs-extra
示例:Node.js教程- Node.js复制文件夹
打印稿版本
async function copyDir(source: string, destination: string): Promise<any> {
const directoryEntries = await readdir(source, { withFileTypes: true });
await mkdir(destination, { recursive: true });
return Promise.all(
directoryEntries.map(async (entry) => {
const sourcePath = path.join(source, entry.name);
const destinationPath = path.join(destination, entry.name);
return entry.isDirectory()
? copyDir(sourcePath, destinationPath)
: copyFile(sourcePath, destinationPath);
})
);
}
目前最上面的答案可以大大简化。
const path = require('path');
const fs = require('fs');
function recursiveCopySync(source, target) {
if (fs.lstatSync(source).isDirectory()) {
if (!fs.existsSync(target)) {
fs.mkdirSync(target);
}
let files = fs.readdirSync(source);
files.forEach((file) => {
recursiveCopySync(path.join(source, file), path.join(target, file));
});
} else {
if (fs.existsSync(source)) {
fs.writeFileSync(target, fs.readFileSync(source));
}
}
}