首页 > 解决方案 > 如何使用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'.

标签: javascriptnode.jsfs

解决方案


暗示您不会在 /Users/Test/tmp/tmp 中复制 /Users/Test/tmp 的内容(这是一个递归错误,会引发您收到的错误消息)

你有两个选择:

  1. 您将 /Users/Test 复制到 /tmp,然后将 /tmp 移动到 /Users/Test/tmp(如果您有 w+ 访问 /tmp 的权限)
  2. 您将 /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;
}

一些评论:

  1. 我没有使用fse.copy的过滤器,因为在过滤源目录dirents之前就抛出了不包含错误
  2. 我使用的是同步版本,因为原始代码看起来不像异步
  3. 我仍然不明白为什么data在函数末尾返回一个参数,但我还是保留了它

推荐阅读