copy a directory in javascript

To copy a directory in JavaScript, we can use the built-in fs (file system) module in Node.js. We will need to use recursion to copy all files and folders within the directory. Here is an example function that copies a directory asynchronously:

index.tsx
const fs = require('fs');
const path = require('path');

function copyDirectory(source, destination, callback) {
  // Create the destination folder if it doesn't exist
  if (!fs.existsSync(destination)) {
    fs.mkdirSync(destination);
  }

  // Read all files/folders in the source directory
  fs.readdir(source, { withFileTypes: true }, (err, files) => {
    if (err) return callback(err);

    // Loop through each file/folder
    files.forEach(file => {
      const sourcePath = path.join(source, file.name);
      const destPath = path.join(destination, file.name);

      // Recursively copy subdirectories
      if (file.isDirectory()) {
        copyDirectory(sourcePath, destPath, callback);
      } else {
        // Copy files
        fs.copyFile(sourcePath, destPath, err => {
          if (err) return callback(err);
        });
      }
    });

    // Callback when all files/folders have been copied
    callback(null);
  });
}
942 chars
34 lines

To use this function, you can call it like this:

index.tsx
const source = './path/to/source';
const destination = './path/to/destination';

copyDirectory(source, destination, err => {
  if (err) console.error(err);
  else console.log('Directory copied successfully!');
});
214 chars
8 lines

Note: This example function only works for asynchronous file copying. If you need synchronous file copying, you can use the fs-extra module which provides a more robust set of file system methods.

gistlibby LogSnag