const fs = require('fs');
const path = require("path");

let sourcePath = path.join(__dirname, "files-copy");
let copyPath = path.join(__dirname, "files");

function createFolder(path) {
    fs.mkdir(path, {
        recursive: true
    }, (err) => {
        if (err) throw err;
    });
}

function copyFiles() {
    fs.readdir(copyPath, {
            withFileTypes: true
        },
        (err, files) => {
            if (err) {
                console.log(err);
            } else {
                files.forEach(file => {
                    let fileSourcePath = path.join(__dirname, "files", file.name);
                    let fileCopyPath = path.join(__dirname, "files-copy", file.name);
                    fs.copyFile(fileSourcePath, fileCopyPath, (err) => {
                        if (err) {
                            console.log("Error Found:", err);
                        }
                    });

                })
            }
        })
}



fs.access(sourcePath, function (error) {
    if (error) {
        createFolder(sourcePath)
        copyFiles()
    } else {
        fs.rm(sourcePath, {
            recursive: true
        }, (err) => {
            if (err) {
                throw err
            } else {
                createFolder(sourcePath)
                copyFiles()
            };
        });

    }
})