ArticleZip > Copy Folder Recursively In Node Js

Copy Folder Recursively In Node Js

Copying folders recursively in Node.js is a handy task that can save you time and effort when working with multiple directories in your projects. In this article, we'll guide you through the process of copying folders recursively using Node.js, providing you with a step-by-step tutorial to help you achieve this efficiently.

To get started, you'll need to have Node.js installed on your machine. If you haven't installed it yet, head over to the official Node.js website and follow the instructions to set it up on your system.

Once you have Node.js ready to go, you can start by creating a new Node.js script file in your project directory. You can name this file whatever you like, for example, `copyFolders.js`.

Next, you'll need to require the `fs` module in Node.js to work with the filesystem. This module provides methods for interacting with files and directories, making it essential for copying folders recursively.

Javascript

const fs = require('fs');

After requiring the `fs` module, you can define a function to copy folders recursively. The function will take two parameters: the source directory and the destination directory where you want to copy the folder.

Javascript

function copyFolderRecursiveSync(source, target) {
    fs.mkdirSync(target, { recursive: true });

    const files = fs.readdirSync(source);

    files.forEach((file) => {
        const current = fs.lstatSync(path.join(source, file));

        if (current.isDirectory()) {
            copyFolderRecursiveSync(path.join(source, file), path.join(target, file));
        } else {
            fs.copyFileSync(path.join(source, file), path.join(target, file));
        }
    });
}

In the `copyFolderRecursiveSync` function, we first create the target directory using `fs.mkdirSync(target, { recursive: true })` to ensure that the full folder structure is copied. We then read the contents of the source directory using `fs.readdirSync(source)` and iterate over each file and directory inside it.

For each item in the source directory, we check if it is a directory or a file using `fs.lstatSync`. If it's a directory, we recursively call the `copyFolderRecursiveSync` function on that directory. If it's a file, we use `fs.copyFileSync` to copy the file into the target directory.

Finally, to initiate the copy process, you can call the `copyFolderRecursiveSync` function with the source and target directories.

Javascript

const sourceDir = 'path/to/sourceDirectory';
const targetDir = 'path/to/targetDirectory';

copyFolderRecursiveSync(sourceDir, targetDir);

By following these steps and using the provided code snippets, you can easily copy folders recursively in Node.js, streamlining your development workflow and saving time when managing directories in your projects.

×