3

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.

1

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This only copies the directory and not it's contents
5

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!");
  }
}); 

1 Comment

What if we only want to copy the files and not recreate the folder structure? How can we do that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.