节点fs复制文件夹

y. *_* lu 8 fs node.js

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

use*_*186 15

您可以使用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!')
});
Run Code Online (Sandbox Code Playgroud)

还有一个同步版本.


Kyl*_*Mit 11

仅用 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用:

copyDir("./inputFolder", "./outputFolder")
Run Code Online (Sandbox Code Playgroud)

进一步阅读


小智 5

您可能想查看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 !");
});
Run Code Online (Sandbox Code Playgroud)