cpx

repository·master·Indexed 19 days ago

https://github.com/mysticatea/cpx

A utility for copying file globs and watching them for changes, providing both a CLI tool and a Node.js API. It supports file synchronization, directory cleaning, and file transformations via shell commands or Node modules. Key features include asynchronous and synchronous copying (cpx.copy, cpx.copySync), and a watching mechanism (cpx.watch) that emits events such as 'copy', 'remove', and 'watch-ready'. Requires Node.js version >=6.5.

Tokens
5K
Snippets
16
Records
23
Agent score
67%

What's inside cpx

  1. Transform files with cpx CLI

    master

    You can transform files during the copy process using either a shell command or a Node.js module.

    Using a shell command:

    $ cpx "src/**/*.js" app -w -c "babel --source-maps inline"

    Using transform modules (e.g., Browserify transforms):

    $ cpx "src/**/*.js" app -w -t babelify -t uglifyify
  2. Use cpx.watch() and its events

    master

    The cpx.watch method copies files matching a glob and then starts observing the files for changes. It returns an EventEmitter that emits events during the watching lifecycle.

    Signature: cpx.watch(source, dest, options) cpx.watch(source, dest)

    Events:

    • copy: Fired after a file is copied. Emits an object with e.srcPath (original) and e.dstPath (new file).
    • remove: Fired when a file is removed. Emits an object with e.path (removed file).
    • watch-ready: Fired when watching starts, after the initial copy is complete.
    • watch-error: Fired when an error occurs during watching. Emits err.
    var cpx = require("cpx");
    
    var watcher = cpx.watch("src/**/*.js", "dist");
    
    watcher.on("copy", (e) => {
      console.log("Copied: " + e.srcPath + " -> " + e.dstPath);
    });
    
    watcher.on("watch-ready", () => {
      console.log("Watching for changes...");
    });
  3. Use cpx.copy() in Node.js

    master

    The cpx.copy method copies files matching a glob to a destination directory. It is asynchronous and accepts a callback.

    Signature: cpx.copy(source, dest, options, callback) cpx.copy(source, dest, callback)

    Options Object:

    • options.clean {boolean}: Remove files copied in the past before the new copy. Default: false.
    • options.dereference {boolean}: Follow symbolic links. Default: false.
    • options.includeEmptyDirs {boolean}: Copy empty directories matched by the glob. Default: false.
    • options.initialCopy {boolean}: If true, performs an initial copy when using cpx.watch(). Default: true.
    • options.preserve {boolean}: Copy uid, gid, atime, and mtime. Default: false.
    • options.transform {((filepath: string) => stream.Transform)[]}: Array of functions that create a stream.Transform object to transform each file.
    • options.update {boolean}: Do not overwrite destination files if the source is older. Default: false.

    Callback:

    • (err: Error|null) => void: Called when the operation completes.
    var cpx = require("cpx");
    
    cpx.copy("src/**/*.js", "dist", { clean: true }, (err) => {
      if (err) console.error(err);
      else console.log("Copy complete");
    });
  4. Configure the Watcher class options

    master

    When instantiating the Watcher class, you can provide an options object to control its behavior. Note that toDestination is a required functional mapping for the watcher to know where to write files.

    OptionTypeDescription
    sourcestringThe glob pattern of source files to match.
    baseDirstringThe root directory to start watching.
    outputDirstringThe path to the output directory.
    toDestinationfunctionA function (string): string that maps a source path to its destination path.
    initialCopybooleanIf true, copies files matching the pattern at the first time the watcher opens.
    cleanbooleanFlag to remove files which are on the destination directory.
    dereferencebooleanFlag to dereference symbolic links.
    includeEmptyDirsbooleanFlag to copy empty directories.
    preservebooleanFlag to copy file attributes such as timestamps, users, and groups.
    updatebooleanFlag to not overwrite newer files.
    transform(function(string):stream.Transform)[]An array of transform function factories to apply to files.
  5. Reference the cpx CLI options

    master

    Available CLI flags for cpx:

    FlagLong FlagDescription
    -c--command <command>A command text to transform each file.
    -C--cleanClean files that match <source> pattern in <dest> before the first copying.
    -L--dereferenceFollow symbolic links when copying from them.
    -h--helpPrint usage information.
    --include-empty-dirsCopy empty directories matched with the glob.
    --no-initialDo not copy at the initial time of watch (use with --watch).
    -p--preserveCopy file attributes (uid, gid, atime, mtime).
    -t--transform <name>Module name to transform each file (loaded via require()).
    -u--updateDo not overwrite files on destination if the source file is older.
    -v--verbosePrint copied/removed files.
    -V--versionPrint the version number.
    -w--watchWatch for changes and copy files to <dest> whenever they change.
  6. Apply file transformations using --transform

    master

    The --transform (or -t) flag allows you to pipe files through a transformation module. The module must be a function that accepts (file, opts) and returns a stream. The opts object will contain _flags which includes the options passed to cpx.

    Example: Using a hypothetical transform module:

    cpx "src/**/*.js" dist --transform "my-transform-module"
  7. Run shell commands on files using --command

    master

    You can use the --command (or -c) flag to execute a shell command for every file that cpx processes. To access the path of the file currently being handled, use the FILE environment variable within your command.

    Example: Using echo to log the file path being processed:

    cpx "src/**/*.js" dist --command "echo Processing $FILE"
  8. Use the cpx CLI

    master

    The cpx CLI tool copies files matching a glob pattern to a destination directory and can watch for changes to perform incremental copies.

    Usage Pattern: cpx <source> <dest> [options]

    Arguments:

    • <source>: The glob pattern of target files.
    • <dest>: The destination directory path.

    Note: When using Bash, enclose your glob in double quotes to prevent the shell from expanding it before it reaches cpx.

    $ cpx "src/**/*.{html,png,jpg}" app --watch
  9. Use the cpx Node.js API

    master

    The cpx module provides a programmatic interface for copying files and watching for changes. You can import the module to access three primary functions:

    • copy(src, dest, [options]): Asynchronously copies files from src to dest.
    • copySync(src, dest, [options]): Synchronously copies files from src to dest.
    • watch(src, dest, [options]): Watches src for changes and copies them to dest whenever a change is detected.
    const cpx = require('cpx');
    
    // Example usage patterns:
    cpx.copy('src/**/*.js', 'dist');
    cpx.copySync('src/**/*.js', 'dist');
    cpx.watch('src/**/*.js', 'dist');
  10. Watcher class methods

    master

    The Watcher class provides the following public methods to control the watching lifecycle:

    • open(): Initializes the watcher, starts the initial copy (if configured), and begins observing the directory tree. Returns void.
    • close(): Stops all active watchers, clears any debounced triggers, and cleans up resources. Returns void.