有没有一种更简单的方法来复制文件夹及其所有内容,而不需要手动递归地执行一系列fs.readir
、fs.readfile
、fs.writefile
操作?
我只是想知道我是否错过了一个理想的工作方式如下的函数:
fs.copy("/path/to/source/folder", "/path/to/destination/folder");
发布于 2012-12-09 17:26:19
有一些模块支持复制文件夹及其内容。最受欢迎的应该是wrench.js
// Deep-copy an existing directory
wrench.copyDirSyncRecursive('directory_to_copy', 'location_where_copy_should_end_up');
另一种选择是node-fs-extra
fs.copy('/tmp/mydir', '/tmp/mynewdir', function (err) {
if (err) {
console.error(err);
} else {
console.log("success!");
}
}); // Copies directory, even if it has subdirectories or files
发布于 2014-03-05 08:04:48
下面是一个将目录及其内容递归复制到另一个目录的函数:
const fs = require("fs")
const path = require("path")
/**
* Look ma, it's cp -R.
* @param {string} src The path to the thing to copy.
* @param {string} dest The path to the new copy.
*/
var copyRecursiveSync = function(src, dest) {
var exists = fs.existsSync(src);
var stats = exists && fs.statSync(src);
var isDirectory = exists && stats.isDirectory();
if (isDirectory) {
fs.mkdirSync(dest);
fs.readdirSync(src).forEach(function(childItemName) {
copyRecursiveSync(path.join(src, childItemName),
path.join(dest, childItemName));
});
} else {
fs.copyFileSync(src, dest);
}
};
发布于 2018-09-15 03:42:30
这就是我个人的做法:
function copyFolderSync(from, to) {
fs.mkdirSync(to);
fs.readdirSync(from).forEach(element => {
if (fs.lstatSync(path.join(from, element)).isFile()) {
fs.copyFileSync(path.join(from, element), path.join(to, element));
} else {
copyFolderSync(path.join(from, element), path.join(to, element));
}
});
}
它适用于文件夹和文件。
https://stackoverflow.com/questions/13786160
复制相似问题