【问题标题】:Node fs copy a folder节点 fs 复制文件夹
【发布时间】:2016-12-30 14:20:39
【问题描述】:

我正在尝试使用 Node fs 模块复制文件夹。我熟悉readFileSync() 和writeFileSync() 方法,但我想知道应该使用什么方法来复制指定的文件夹?

【问题讨论】:

标签: node.js fs


【解决方案1】:

您可能想查看ncp 包。它完全符合您的要求;递归地将文件从一个路径复制到另一个路径。

这里有一些让你开始的东西:

const fs = require("fs");
const path = require("path");
const ncp = require("ncp").ncp;
// No limit, because why not?
ncp.limit = 0;

var thePath = "./";
var folder = "testFolder";
var newFolder = "newTestFolder";

ncp(path.join(thePath, folder), path.join(thePath, newFolder), function (err) {
    if (err) {
        return console.error(err);
    }
    console.log("Done !");
});

【讨论】:

  • 为什么有人会选择ncp 而不是fs-extra?
  • 有很多理由选择一种工具而不是另一种。回到我写那个答案的时候,它是我完成这项任务的首选包。现在使用fs-extra 可能会更好,但这并不意味着我在写它时的答案很糟糕。
  • 我并没有暗示你的回答不好。我只是对自己很好奇。谢谢
  • ncp 可以递归复制文件夹中的文件,而 fs-extra 只复制文件夹下的文件
  • fs-extra 也像 ncp 一样递归地复制所有文件。在复制文件夹方面,我看不出它们之间有什么区别。
【解决方案2】:

您可以像这样使用fs-extra 将一个文件夹的内容复制到另一个文件夹

var fs = require("fs-extra");

fs.copy('/path/to/source', '/path/to/destination', function (err) {
  if (err) return console.error(err)
  console.log('success!')
});

还有一个同步版本。

【讨论】:

    【解决方案3】:

    有一种优雅的语法。您可以使用pwd-fs 模块。

    const FileSystem = require('pwd-fs');
    const pfs = new FileSystem();
    
    async () => {
      await pfs.copy('./path', './dest');
    }
    

    【讨论】:

      【解决方案4】:

      只需 10 行本机节点函数即可为自己节省额外的依赖

      添加以下copyDir函数:

      const { promises: fs } = require("fs")
      const path = require("path")
      
      async function copyDir(src, dest) {
          await fs.mkdir(dest, { recursive: true });
          let entries = await fs.readdir(src, { withFileTypes: true });
      
          for (let entry of entries) {
              let srcPath = path.join(src, entry.name);
              let destPath = path.join(dest, entry.name);
      
              entry.isDirectory() ?
                  await copyDir(srcPath, destPath) :
                  await fs.copyFile(srcPath, destPath);
          }
      }
      

      然后像这样使用:

      copyDir("./inputFolder", "./outputFolder")
      

      进一步阅读

      【讨论】:

      • 我真的很喜欢避免额外依赖的想法。我认为我们中很少有人真正意识到“香草节点”固有的功能。
      • 很棒的方法,谢谢!
      • 谢谢,这太棒了,避免使用 glob、fs-extra 和其他依赖项,你是我的英雄!
      【解决方案5】:

      这是@KyleMit answer的同步版本

      copyDirectory(source, destination) {
          fs.mkdirSync(destination, { recursive: true });
          
          fs.readdirSync(source, { withFileTypes: true }).forEach((entry) => {
            let sourcePath = path.join(source, entry.name);
            let destinationPath = path.join(destination, entry.name);
      
            entry.isDirectory()
              ? copyDirectory(sourcePath, destinationPath)
              : fs.copyFileSync(sourcePath, destinationPath);
          });
        }
      

      【讨论】:

        【解决方案6】:

        我喜欢KyleMit's answer,但认为并行版本会更好。

        代码在 TypeScript 中。如果需要JavaScript,只需删除copyDirectory声明行上的: string类型注解即可。

        import { promises as fs } from "fs"
        import path from "path"
        
        export const copyDirectory = async (src: string, dest: string) => {
          const [entries] = await Promise.all([
            fs.readdir(src, { withFileTypes: true }),
            fs.mkdir(dest, { recursive: true }),
          ])
        
          await Promise.all(
            entries.map((entry) => {
              const srcPath = path.join(src, entry.name)
              const destPath = path.join(dest, entry.name)
              return entry.isDirectory()
                ? copyDirectory(srcPath, destPath)
                : fs.copyFile(srcPath, destPath)
            })
          )
        }
        

        【讨论】:

          猜你喜欢
          • 2015-11-06
          • 2014-02-28
          • 2023-03-12
          • 1970-01-01
          • 2023-01-28
          • 2020-08-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多