【发布时间】:2016-12-30 14:20:39
【问题描述】:
我正在尝试使用 Node fs 模块复制文件夹。我熟悉readFileSync() 和writeFileSync() 方法,但我想知道应该使用什么方法来复制指定的文件夹?
【问题讨论】:
我正在尝试使用 Node fs 模块复制文件夹。我熟悉readFileSync() 和writeFileSync() 方法,但我想知道应该使用什么方法来复制指定的文件夹?
【问题讨论】:
您可能想查看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 可能会更好,但这并不意味着我在写它时的答案很糟糕。
您可以像这样使用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!')
});
还有一个同步版本。
【讨论】:
有一种优雅的语法。您可以使用pwd-fs 模块。
const FileSystem = require('pwd-fs');
const pfs = new FileSystem();
async () => {
await pfs.copy('./path', './dest');
}
【讨论】:
只需 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")
fsPromises.copyFile (添加于v10.11.0)
fsPromises.readdir (添加于v10.0)
fsPromises.mkdir (添加于v10.0)
【讨论】:
这是@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);
});
}
【讨论】:
我喜欢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)
})
)
}
【讨论】: