Node fs copy a folder

24,904

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

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)
    })
  )
}
Share:
24,904

Related videos on Youtube

y. lu
Author by

y. lu

Updated on July 28, 2021

Comments

  • y. lu
    y. lu almost 3 years

    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?

  • A. Wentzel
    A. Wentzel over 5 years
    Why would someone choose ncp over fs-extra?
  • fdrobidoux
    fdrobidoux over 5 years
    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.
  • A. Wentzel
    A. Wentzel over 5 years
    I was not insinuating your answer was bad. I was just curious for myself. Thanks
  • Tianzhen Lin
    Tianzhen Lin about 5 years
    ncp can copy files in a folder recursively whereas fs-extra only copies files directly under the folder
  • vivek_reddy
    vivek_reddy about 4 years
    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.
  • Jon Trauntvein
    Jon Trauntvein almost 3 years
    I 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
    matantan over 2 years
    Amazing approach, thanks man!
  • DavidZam
    DavidZam over 2 years
    Thanks man, this is amazing, avoid glob, fs-extra, and other dependencies using this stuff, you're my hero!