2

I'm looking for a way to copy a folder's content to another folder or even replace the folder if it exists with the old one but preserve its name.

Thanks for helping.

  • **See Also**: [Copy folder recursively in node.js](https://stackoverflow.com/q/13786160/1366033) – KyleMit Oct 08 '20 at 03:32

2 Answers2

5

First install fs-extra module in your project by doing npm install fs-extra then follow the steps below:

import the following

var fs = require('fs');
var fs_Extra = require('fs-extra');
var path = require('path');

// Here you declare your path

var sourceDir = path.join(__dirname, "../working");
var destinationDir = path.join(__dirname, "../worked")

// if folder doesn't exists create it

if (!fs.existsSync(destinationDir)){
    fs.mkdirSync(destinationDir, { recursive: true });
}

// copy folder content

fs_Extra.copy(sourceDir, destinationDir, function(error) {
    if (error) {
        throw error;
    } else {
      console.log("success!");
    }
}); 

NB: source and destination folder name should not be the same.

Raul
  • 800
  • 1
  • 7
  • 22
Emmanuel Ani
  • 432
  • 5
  • 10
4

First check if the destination path exists if not create it, then you could use fs-extra for the copying of files/subdirectories.

var fs = require('fs');
var fse = require('fs-extra');

var sourceDir = '/tmp/mydir';
var destDir = '/tmp/mynewdir';


// if folder doesn't exists create it
if (!fs.existsSync(destDir)){
    fs.mkdirSync(destDir, { recursive: true });
}

//copy directory content including subfolders
fse.copy(sourceDir, destDir, function (err) {
  if (err) {
    console.error(err);
  } else {
    console.log("success!");
  }
}); 
Erwin van Hoof
  • 957
  • 5
  • 17