or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-cpr

Cross-platform recursive file copying library that replicates Unix 'cp -R' command functionality

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/cpr@3.0.x

To install, run

npx @tessl/cli install tessl/npm-cpr@3.0.0

index.mddocs/

CPR

CPR (cp -R) is a cross-platform recursive file copying library for Node.js that replicates the functionality of the Unix cp -R command. It provides both a JavaScript API and a command-line interface for copying files and directories recursively with various options including overwrite protection, destination deletion before copying, file filtering, and post-copy verification.

Package Information

  • Package Name: cpr
  • Package Type: npm
  • Language: JavaScript with TypeScript definitions
  • Installation: npm install cpr

Core Imports

const cpr = require('cpr');

For backward compatibility:

const { cpr } = require('cpr');

Basic Usage

const cpr = require('cpr');

// Simple copy
cpr('/path/from', '/path/to', function(err, files) {
    if (err) {
        console.error('Copy failed:', err);
        return;
    }
    console.log('Copied files:', files);
});

// Copy with options
cpr('/path/from', '/path/to', {
    deleteFirst: true,  // Delete destination before copying
    overwrite: true,    // Overwrite existing files
    confirm: true,      // Verify all files copied successfully
    filter: /\.txt$/    // Only copy .txt files
}, function(err, files) {
    if (err) {
        console.error('Copy failed:', err.message);
        if (err.list) {
            console.error('Failed operations:', err.list);
        }
        return;
    }
    console.log('Successfully copied', files.length, 'files');
});

Capabilities

Main Copy Function

Core recursive file copying functionality with comprehensive options for file system operations.

/**
 * Recursively copy files and directories from source to destination
 * @param {string} from - Source file or directory path
 * @param {string} to - Destination file or directory path
 * @param {CprOptions} [options] - Copy configuration options
 * @param {function} [callback] - Completion callback (err, files) => void
 */
function cpr(from, to, options, callback);

/**
 * Copy options configuration
 * @typedef {Object} CprOptions
 * @property {boolean} [deleteFirst] - Delete destination directory before copying using rimraf
 * @property {boolean} [overwrite] - Overwrite existing files at destination
 * @property {boolean} [confirm] - Verify all files copied successfully after operation completes
 * @property {RegExp|function} [filter] - Filter files/directories during copy operation
 */

Parameters:

  • from (string): Source file or directory path to copy from
  • to (string): Destination file or directory path to copy to
  • options (CprOptions, optional): Configuration options object
  • callback (function, optional): Completion callback with signature (err, files) => void

Callback Parameters:

  • err (Error | null): Error object if copy failed, may include err.list array of individual operation errors
  • files (string[]): Array of destination file paths that were successfully copied

Usage Examples:

const cpr = require('cpr');

// Copy directory with all options
cpr('./source', './destination', {
    deleteFirst: true,  // Remove destination first
    overwrite: true,    // Replace existing files
    confirm: true,      // Verify completion
    filter: function(path) {
        // Custom filter function - return true to include file
        return !path.includes('node_modules');
    }
}, function(err, files) {
    if (err) {
        console.error('Error:', err.message);
        return;
    }
    console.log('Copied:', files);
});

// Copy with regex filter
cpr('./docs', './build/docs', {
    filter: /\.(md|txt)$/i  // Only copy markdown and text files
}, function(err, files) {
    if (err) return console.error(err);
    console.log('Documentation copied');
});

// Copy single file
cpr('./package.json', './backup/package.json', {
    overwrite: true
}, function(err, files) {
    if (err) return console.error(err);
    console.log('Backup created');
});

Backward Compatibility Export

Legacy export for backward compatibility with older versions.

/**
 * Backward compatibility alias for the main cpr function
 * @param {string} from - Source path
 * @param {string} to - Destination path
 * @param {CprOptions} [options] - Copy options
 * @param {function} [callback] - Completion callback
 */
cpr.cpr(from, to, options, callback);

Command Line Interface

CPR provides a command-line interface for cross-platform file copying operations.

CLI Usage

cpr <source> <destination> [options]

CLI Options

-d, --delete-first              Delete the destination directory before copying
-f <regex>, --filter <regex>    Filter out items matching case-insensitive regex pattern  
-h, --help                      Display usage information
-o, --overwrite                 Overwrite destination if it exists
-v, --version                   Display cpr version

CLI Examples:

# Basic copy
cpr ./src ./build

# Copy with options
cpr ./source ./dest --delete-first --overwrite

# Copy with filtering
cpr ./docs ./output --filter "\.tmp$"

# Show help
cpr --help

# Show version
cpr --version

TypeScript Support

CPR includes complete TypeScript definitions for type-safe usage.

declare function cpr(
    from: string, 
    to: string, 
    options?: CprOptions, 
    callback?: (err: any, files: string[]) => void
): void;

interface CprOptions {
    deleteFirst?: boolean;
    overwrite?: boolean;
    confirm?: boolean;
    filter?: RegExp | ((path: string) => boolean);
}

File Filtering

CPR supports two types of file filtering for selective copying operations.

RegExp Filtering

When a RegExp is provided as the filter, it tests the full absolute pathname of each file and directory. Files matching the pattern are excluded from copying.

// Exclude all .log files
cpr('./app', './backup', {
    filter: /\.log$/i
}, callback);

// Exclude node_modules and .git directories
cpr('./project', './copy', {
    filter: /(node_modules|\.git)/
}, callback);

Function Filtering

When a function is provided as the filter, it receives the full absolute pathname and should return true to include the file in copying.

// Only copy JavaScript files
cpr('./src', './dist', {
    filter: function(path) {
        return path.endsWith('.js') || require('fs').statSync(path).isDirectory();
    }
}, callback);

// Copy files modified in last 7 days
cpr('./docs', './recent', {
    filter: function(path) {
        const stat = require('fs').statSync(path);
        const week = 7 * 24 * 60 * 60 * 1000;
        return Date.now() - stat.mtime.getTime() < week;
    }
}, callback);

Error Handling

CPR provides comprehensive error reporting for robust file system operations.

Error Types

  • ENOTDIR: Target exists and is not a directory when directory creation attempted
  • EEXIST: File exists at destination when overwrite: false (default)
  • EMFILE: Too many open files (handled gracefully with retries)

Error Object Properties

/**
 * Error object returned in callback when operations fail
 * @typedef {Error} CprError
 * @property {string} message - Error description
 * @property {string} code - Error code (ENOTDIR, EEXIST, etc.)
 * @property {number} errno - System error number
 * @property {Array<Error>} [list] - Array of individual operation errors for detailed diagnostics
 */

Error Handling Example:

cpr('./source', './destination', function(err, files) {
    if (err) {
        console.error('Copy operation failed:', err.message);
        
        // Check for detailed error list
        if (err.list && err.list.length > 0) {
            console.error('Individual failures:');
            err.list.forEach((error, index) => {
                console.error(`  ${index + 1}. ${error.message}`);
            });
        }
        return;
    }
    
    console.log('Successfully copied', files.length, 'files');
});

Cross-Platform Compatibility

CPR is designed for reliable cross-platform operation across Windows, macOS, and Linux systems.

Platform Features

  • Path Handling: Automatic path separator normalization
  • File Permissions: Preserves file mode permissions where supported
  • Symbolic Links: Handles symbolic links appropriately per platform
  • Large Files: Streaming-based copying for memory efficiency
  • File Locking: Graceful handling of locked files on Windows

Dependencies

CPR relies on these packages for cross-platform reliability:

  • graceful-fs: Enhanced file system operations with better error handling
  • mkdirp: Recursive directory creation
  • rimraf: Cross-platform recursive directory removal
  • minimist: Command-line argument parsing