Node.js Copy a Folder Recursively using fs-extra

Node.js Copy a Folder – In this tutorial, we shall learn how to copy a folder or directory recursively in Node.js. A recursive copy means the source directory, its files, subfolders, and files inside those subfolders are copied to another location.

We shall use the fs-extra package because it provides a simple copy() method for copying directories, including nested folder structures. This is useful when you need to copy assets, templates, generated files, build folders, or project directories in a Node.js script.

Install Node fs-extra package

To Install Node fs-extra package using NPM (Node Package Manager), run the following command in Terminal.

$ npm install fs-extra

If you are creating a new Node.js project, initialise the project first and then install fs-extra.

</>
Copy
npm init -y
npm install fs-extra

Folder Structure used in this Node.js copy folder example

Assume that the source folder is named folderA. It may contain normal files and nested folders as shown below.

folderA/
  file1.txt
  file2.txt
  images/
    logo.png
  docs/
    readme.txt

After the script runs successfully, the destination folder folderB will contain the copied files and subfolders.

folderB/
  file1.txt
  file2.txt
  images/
    logo.png
  docs/
    readme.txt

Example – Copy Folder using Node FS Extra

In this example, we will copy a folder “folderA” to folder “folderB” using fs.copy() method.

node-js-copy-a-foder.js

</>
Copy
// include fs-extra package
var fs = require("fs-extra");

var source = 'folderA'
var destination = 'folderB'

// copy source folder to destination
fs.copy(source, destination, function (err) {
	if (err){
		console.log('An error occured while copying the folder.')
		return console.error(err)
	}
	console.log('Copy completed!')
});

Open a terminal or command prompt and run this script using node command as shown in the following.

Output

arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node node-js-copy-a-foder.js
Copy completed!

Copy a folder recursively in Node.js using async and await

The callback example works, but in modern Node.js projects you may prefer the Promise-based form of fs.copy(). When you do not pass a callback, fs.copy() returns a Promise, so it can be used with async and await.

copy-folder-async.js

</>
Copy
const fs = require('fs-extra');

async function copyFolder() {
  const source = 'folderA';
  const destination = 'folderB';

  try {
    await fs.copy(source, destination);
    console.log('Folder copied successfully.');
  } catch (error) {
    console.error('Error while copying folder:', error);
  }
}

copyFolder();

Run the script from the same directory where folderA is present.

</>
Copy
node copy-folder-async.js
Folder copied successfully.

Copy a folder only when the destination does not already exist

By default, copying into an existing destination may overwrite matching files. If your script should avoid overwriting an existing folder, check whether the destination exists before calling fs.copy().

copy-folder-if-not-exists.js

</>
Copy
const fs = require('fs-extra');

async function copyFolderIfNotExists() {
  const source = 'folderA';
  const destination = 'folderB';

  try {
    const destinationExists = await fs.pathExists(destination);

    if (destinationExists) {
      console.log('Destination folder already exists. Copy skipped.');
      return;
    }

    await fs.copy(source, destination);
    console.log('Folder copied successfully.');
  } catch (error) {
    console.error('Error while copying folder:', error);
  }
}

copyFolderIfNotExists();

This approach is useful when you are copying starter templates, default configuration folders, or sample assets and you do not want to replace user-modified files.

Copy selected files while copying a Node.js folder

The filter option can be used when you want to skip some files or folders during the copy. The following example copies the folder but skips node_modules and .git directories.

copy-folder-with-filter.js

</>
Copy
const fs = require('fs-extra');
const path = require('path');

async function copyFolderWithFilter() {
  const source = 'folderA';
  const destination = 'folderB';

  try {
    await fs.copy(source, destination, {
      filter: (src) => {
        const name = path.basename(src);
        return name !== 'node_modules' && name !== '.git';
      }
    });

    console.log('Folder copied with filter.');
  } catch (error) {
    console.error('Error while copying folder:', error);
  }
}

copyFolderWithFilter();

Filtering is helpful for project-copy scripts because folders such as node_modules, build outputs, logs, and version-control folders are often not required in the copied destination.

Use absolute paths when copying folders from another location

The examples above use relative paths such as folderA and folderB. A relative path is resolved from the directory where the Node.js process is started. If the script may be run from different folders, use path.join() with __dirname to build reliable paths.

</>
Copy
const fs = require('fs-extra');
const path = require('path');

async function copyUsingAbsolutePaths() {
  const source = path.join(__dirname, 'folderA');
  const destination = path.join(__dirname, 'folderB');

  try {
    await fs.copy(source, destination);
    console.log('Folder copied using absolute paths.');
  } catch (error) {
    console.error(error);
  }
}

copyUsingAbsolutePaths();

Common errors while copying a folder in Node.js

When a folder copy fails, the cause is usually related to an incorrect path, missing permissions, or an existing destination file with the same name. The error object printed in the catch block or callback helps identify the exact reason.

Error or situationWhat to check
Source folder not foundConfirm that folderA exists relative to the directory where you run the script.
Permission deniedCheck read permission for the source folder and write permission for the destination location.
Destination already has filesDecide whether overwriting is acceptable. If not, check the destination before copying.
Unexpected folder locationUse __dirname and path.join() instead of relying only on relative paths.

fs-extra copy() versus Node.js built-in fs.cp()

Recent versions of Node.js include built-in file-system methods that can copy directories recursively. However, many projects still use fs-extra because it provides convenient helpers such as copy(), ensureDir(), pathExists(), and other file operations with a consistent API.

If your project already uses fs-extra, fs.copy() is simple and readable. If you are avoiding external dependencies and your Node.js version supports the built-in recursive copy API you need, the native fs module may also be suitable.

QA checklist for this Node.js folder copy script

  • Confirm that the source folder path is correct before running the script.
  • Test the script with a folder that contains at least one nested subfolder.
  • Decide whether existing destination files should be overwritten or protected.
  • Use try...catch or a callback error check so failed copy operations are visible.
  • Use absolute paths if the script may be executed from different working directories.

FAQs on copying a folder in Node.js using fs-extra

Does fs-extra copy folders recursively?

Yes. The fs.copy() method from fs-extra can copy a directory recursively, including files and nested subfolders.

Does fs.copy() create the destination folder automatically?

Yes. If the destination path does not exist, fs.copy() creates the required destination folders while copying.

Can I use async and await with fs-extra copy()?

Yes. If you call fs.copy() without a callback, it returns a Promise. You can use it inside an async function with await.

How do I skip node_modules while copying a folder?

Use the filter option in fs.copy(). Return false for paths that should not be copied, such as node_modules or .git.

Should I use fs-extra or the built-in fs module to copy a folder?

Use fs-extra when you want a simple helper API and are already comfortable adding the dependency. Use the built-in fs module when your Node.js version supports the required copy behavior and you want to avoid an extra package.

Conclusion

In this Node.js Tutorial – Node FS – Node.js Copy a Folder, we have learnt to install Node fs-extra package and to copy a folder or directory recursively to another location using fs.copy(). We also covered async and await usage, destination checks, filtered copying, path handling, and common errors that may occur while copying folders in Node.js.