Recursive File Copy Utility

2.0.14 · active · verified Sun Apr 19

recursive-copy is a robust and flexible utility for copying files and directories within a Node.js environment. It is currently stable at version 2.0.14 and appears to be actively maintained, with a focus on reliability and advanced use cases for filesystem operations. Key features include recursive directory copying, sophisticated filtering using functions, regular expressions, or globs, dynamic file renaming, and stream-based content transformation. It differentiates itself by integrating with `graceful-fs` and `mkdirp` to handle common filesystem errors, automatically filters out OS junk files by default, and provides an event-driven interface alongside traditional callback and promise-based APIs. This makes it suitable for complex build processes or file manipulation tasks where fine-grained control and error handling are crucial, offering a more feature-rich alternative to basic `fs.copyFile` or `fs.cp` methods.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to recursively copy a directory, including dotfiles, with specific filters, using the promise-based `async/await` syntax. It also includes cleanup.

import copy from 'recursive-copy';
import path from 'path';
import fs from 'fs';

const sourceDir = path.join(process.cwd(), 'temp_src');
const destDir = path.join(process.cwd(), 'temp_dest');

// Create dummy source files for demonstration
fs.mkdirSync(sourceDir, { recursive: true });
fs.writeFileSync(path.join(sourceDir, 'file1.txt'), 'Hello world!');
fs.writeFileSync(path.join(sourceDir, '.dotfile'), 'Hidden content.');
fs.mkdirSync(path.join(sourceDir, 'subdir'), { recursive: true });
fs.writeFileSync(path.join(sourceDir, 'subdir', 'file2.js'), 'console.log("JS file");');

async function runCopyExample() {
  try {
    console.log(`Copying from ${sourceDir} to ${destDir}...`);
    const results = await copy(sourceDir, destDir, {
      overwrite: true, // Overwrite if destination files exist
      dot: true,     // Copy dotfiles
      filter: ['**/*', '!*.log'] // Copy all files except .log files
    });
    console.info(`Copied ${results.length} files successfully.`);
    results.forEach(op => console.log(`  - ${op.src} -> ${op.dest}`));
  } catch (error) {
    console.error('Copy failed: ' + error.message);
  } finally {
    // Clean up temporary directories
    fs.rmSync(sourceDir, { recursive: true, force: true });
    fs.rmSync(destDir, { recursive: true, force: true });
    console.log('Temporary directories cleaned up.');
  }
}

runCopyExample();

view raw JSON →