29

I am trying to copy a folder using Node fs module. I am familiar with readFileSync() and writeFileSync() methods but I am wondering what method I should use to copy a specified folder?

peteb
  • 16,991
  • 8
  • 49
  • 59
y. lu
  • 291
  • 1
  • 3
  • 4
  • 10
    Possible duplicate of [Copy folder recursively in node.js](http://stackoverflow.com/questions/13786160/copy-folder-recursively-in-node-js) – Chad Robinson Aug 23 '16 at 16:41

6 Answers6

35

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')
dinodsaurus
  • 4,771
  • 4
  • 18
  • 24
user3248186
  • 1,428
  • 4
  • 20
  • 34
27

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

KyleMit
  • 35,223
  • 60
  • 418
  • 600
4

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 !");
});
fdrobidoux
  • 291
  • 3
  • 10
  • 1
    Why would someone choose `ncp` over `fs-extra`? – A. Wentzel Feb 12 '19 at 18:04
  • 1
    There 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. – fdrobidoux Feb 27 '19 at 02:09
  • I was not insinuating your answer was bad. I was just curious for myself. Thanks – A. Wentzel Feb 27 '19 at 21:25
  • 1
    ncp can copy files in a folder recursively whereas fs-extra only copies files directly under the folder – Tianzhen Lin Jun 26 '19 at 14:09
  • fs-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. – vivek_reddy Apr 05 '20 at 18:49
1

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);
    });
  }
Eonasdan
  • 7,287
  • 8
  • 52
  • 79
1

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)
    })
  )
}
Anders
  • 11
  • 1
0

There is an elegant syntax. You can use the pwd-fs module.

const FileSystem = require('pwd-fs');
const pfs = new FileSystem();

async () => {
  await pfs.copy('./path', './dest');
}