javascript - 如何使用nodejs fs将父目录文件复制到子目录?
问题描述
在尝试将父内容复制到子目录时,它会抛出以下错误。有没有人知道我在哪里做错了,有没有更好的方法来完成这项任务?
main.js
const fse = require('fs-extra');
const copyDirectories = function(data) {
let source ='/Users/Test';
let destination = '/Users/Test/tmp';
fse.copy(source, destination)
.then(() => console.log('Copy completed!'))
.catch( err => {
console.log('An error occured while copying the folder.')
return console.error(err)
})
return data;
}
错误
Cannot copy '/Users/Test' to a subdirectory of itself, '/Users/Test/tmp'.
解决方案
暗示您不会在 /Users/Test/tmp/tmp 中复制 /Users/Test/tmp 的内容(这是一个递归错误,会引发您收到的错误消息)
你有两个选择:
- 您将 /Users/Test 复制到 /tmp,然后将 /tmp 移动到 /Users/Test/tmp(如果您有 w+ 访问 /tmp 的权限)
- 您将 /Users/Test 的所有条目(不包括 /Users/Test/tmp)复制到 /Users/Test/tmp
我认为没有其他选择。
选项 2 的代码示例:
const fs = require("fs");
const fse = require('fs-extra');
const copyDirectories = (data, source, destination) => {
fs.readdirSync(source,{withFileTypes: true}).filter(
(entry) => {
const fullsrc = path.resolve(source + path.sep + entry.name);
const fulldest= path.resolve(destination + path.sep + entry.name);
if(entry.isDirectory && fullsrc !== destination)
fse.copySync(fullsrc, fulldest);
else if(!entry.isDirectory)
fs.copySync(fullsrc, fulldest);
return true;
}
);
return data;
}
一些评论:
- 我没有使用fse.copy的过滤器,因为在过滤源目录dirents之前就抛出了不包含错误
- 我使用的是同步版本,因为原始代码看起来不像异步
- 我仍然不明白为什么
data
在函数末尾返回一个参数,但我还是保留了它
推荐阅读
- javascript - React - 将图像框包装器格式化为中心
- angular - 针对 Apache Karaf Froms 身份验证的 Angular Ajax 身份验证
- validation - 使用 Slice 的指针转换接口以迭代其值
- google-analytics - GA4 - GA4 中的用户 ID 报告和 BigQuery 中的利用
- excel - 由于循环引用,Excel 文件无法打开
- vba - VBA for MS-Word 中页眉和页脚中的内容控件中的超链接
- xpath - 选择位于两个元素之间的元素
- python - Python sorted() ab = ab0
- javascript - 您如何使用由 javascript 控制的 php 进行复选框输入?
- parsing - getPageSource 不适用于 RSelenium