Node fs copy a folder
Solution 1
You can use fs-extra to copy contents of one folder to another like this
var fs = require("fs-extra");
fs.copy('/path/to/source', '/path/to/destination', function (err) {
if (err) return console.error(err)
console.log('success!')
});
There's also a synchronous version.
fs.copySync('/path/to/source', '/path/to/destination')
Solution 2
Save yourself the extra dependency with just 10 lines of native node functions
Add the following copyDir
function:
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);
}
}
And then use like this:
copyDir("./inputFolder", "./outputFolder")
Further Reading
- Copy folder recursively in node.js
-
fsPromises.copyFile
(added inv10.11.0
) -
fsPromises.readdir
(added inv10.0
) -
fsPromises.mkdir
(added inv10.0
)
Solution 3
You might want to check out the ncp package. It does exactly what you're trying to do; Recursively copy files from a path to another.
Here's something to get your started :
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 !");
});
Solution 4
Here's the synchronous version of @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);
});
}
Solution 5
I liked KyleMit's answer, but thought a parallel version would be preferable.
The code is in TypeScript. If you need JavaScript, just delete the : string
type annotations on the line of the declaration of copyDirectory
.
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)
})
)
}
Related videos on Youtube
y. lu
Updated on July 28, 2021Comments
-
y. lu almost 3 years
I am trying to copy a folder using Node
fs
module. I am familiar withreadFileSync()
andwriteFileSync()
methods but I am wondering what method I should use to copy a specified folder?-
Chad Robinson almost 8 yearsPossible duplicate of Copy folder recursively in node.js
-
-
A. Wentzel over 5 yearsWhy would someone choose
ncp
overfs-extra
? -
fdrobidoux over 5 yearsThere are plenty of reasons to choose one tool over another. Back when I wrote that answer, it was the package I prefered for accomplishing that task. Nowadays it might be better to use
fs-extra
, but that doesn't mean my answer was bad at the time I wrote it. -
A. Wentzel over 5 yearsI was not insinuating your answer was bad. I was just curious for myself. Thanks
-
Tianzhen Lin about 5 yearsncp can copy files in a folder recursively whereas fs-extra only copies files directly under the folder
-
vivek_reddy about 4 yearsfs-extra also copies all the files recursively just like ncp does. I don't see any difference between them in terms of copying a folder.
-
Jon Trauntvein almost 3 yearsI really like the idea of avoiding the extra dependencies. I think that few of us actually realise the capabilities that are inherent in "vanilla node".
-
matantan over 2 yearsAmazing approach, thanks man!
-
DavidZam over 2 yearsThanks man, this is amazing, avoid glob, fs-extra, and other dependencies using this stuff, you're my hero!