copy a directory in typescript

To copy a directory in TypeScript, you can use the built-in file system (fs) module which is available in Node.js. Here's an example code snippet that demonstrates the process:

index.ts
import * as fs from 'fs';

const copyDirectory = (source: string, destination: string) => {
    if (!fs.existsSync(destination)) {
        fs.mkdirSync(destination);
    }

    // Read all files/folders in the source directory
    const files = fs.readdirSync(source);

    // Copy each file/folder to the destination directory
    files.forEach(file => {
        const currentPath = `${source}/${file}`;
        const newPath = `${destination}/${file}`;

        if (fs.statSync(currentPath).isDirectory()) {
            // Recursively copy a subdirectory
            copyDirectory(currentPath, newPath);
        } else {
            // Copy a file
            fs.copyFileSync(currentPath, newPath);
        }
    });
};

// Example usage
copyDirectory('path/to/source/directory', 'path/to/destination/directory');
816 chars
28 lines

This code uses fs.readdirSync to get a list of all files and folders in the source directory, and then iterates over them, checking if each item is a file or a folder using fs.statSync. If the item is a folder, the copyDirectory function is called recursively with the subdirectory as the new source and destination paths. If the item is a file, it is copied using fs.copyFileSync. Before copying anything, we also check if the destination directory exists, and create it using fs.mkdirSync if it doesn't.

gistlibby LogSnag