Copy folder content to another folder with nodejs

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.

Upvotes: 3

Views: 12350

Answers (2)

Emmanuel Ani
Emmanuel Ani

Reputation: 462

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.

Upvotes: 5

Erwin van Hoof
Erwin van Hoof

Reputation: 1012

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

Upvotes: 5

Related Questions