### Copy with options Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy.md Utilize this example to copy files while preserving attributes, following symbolic links, and only updating older destination files. ```javascript cpx.copy("src/**/*.css", "app", { preserve: true, dereference: true, update: true, }).then(() => console.log("Copied with attributes preserved")); ``` -------------------------------- ### Start Watching Files with Watcher.open() Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/watcher.md Initiates file system watching. This method is automatically called when a Watcher is created via `cpx.watch()`. ```typescript open(): void ``` ```javascript const watcher = new Watcher(options); watcher.open(); ``` -------------------------------- ### Copy HTML and CSS files at any depth Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/configuration.md This example shows how to copy HTML and CSS files from any subdirectory within 'src' to the 'app' directory. ```bash cpx "src/**/*.{html,css}" app ``` -------------------------------- ### Browserify Transform Example with cpx API Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/configuration.md Demonstrates how to use the `transform` option in the cpx Node.js API to apply a Babel transform to JavaScript files during copying. Requires `babelify` to be installed. ```javascript const cpx = require("cpx"); const babelify = require("babelify"); cpx.copy("src/**/*.js", "lib", { transform: [ (filepath, options) => babelify(filepath, { presets: ["@babel/preset-env"], }), ], }); ``` -------------------------------- ### One-Time Cleanup of Temporary Files Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/remove-file-sync.md This example demonstrates how to perform a one-time cleanup of temporary or stale files using a wildcard pattern. ```javascript applyActionSync("dist/**/*.tmp", options, targetPath => { removeFileSync(targetPath); }); ``` -------------------------------- ### Basic Watch Example Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/watch.md Demonstrates how to watch for file changes in a source directory and copy them to a destination. Includes event listeners for copy, remove, ready, and error events. ```javascript const cpx = require("cpx"); const watcher = cpx.watch("src/**/*.js", "dist"); watcher.on("copy", (e) => { console.log(`Copied: ${e.srcPath} -> ${e.dstPath}`); }); watcher.on("remove", (e) => { console.log(`Removed: ${e.path}`); }); watcher.on("watch-ready", () => { console.log("Watching for changes..."); }); watcher.on("watch-error", (err) => { console.error("Watch error:", err); }); ``` -------------------------------- ### Basic Synchronous File Copy Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy-file-sync.md Demonstrates a basic synchronous file copy operation. Ensure the 'cpx' module is installed and imported correctly. This example copies 'src/file.js' to 'dist/file.js' without preserving attributes or updating if the destination is newer. ```javascript const copyFileSync = require("./lib/utils/copy-file-sync"); try { copyFileSync("src/file.js", "dist/file.js", { preserve: false, update: false, }); console.log("File copied"); } catch (err) { console.error("Copy failed:", err); } ``` -------------------------------- ### Node.js API Example using Shell Command Transform Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/configuration.md This example demonstrates the conceptual usage of the `--command` option within the cpx Node.js API, although it's typically more practical via the CLI. It highlights the use of the `$FILE` environment variable for shell commands. ```javascript const cpx = require("cpx"); cpx.copy("src/**/*.txt", "output", { // Transform via shell command using FILE environment variable // This would typically be done via CLI, not the API }).catch(err => console.error(err)); ``` -------------------------------- ### Basic Watch Example Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/watch.md Watch all JavaScript files in the src directory and its subdirectories, copying them to the dist directory. The copy is performed immediately and then on any changes. ```typescript import * as cpx from 'cpx'; cpx.watch('src/**/*.js', 'dist'); ``` -------------------------------- ### Cross-Platform Path Normalization Example Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/normalize-path.md Demonstrates how normalizePath handles Windows paths with backslashes by converting them to forward slashes, ensuring compatibility with modules like 'glob'. ```bash # Windows path with backslashes "src\\files\\*.js" -> "src/files/*.js" # Unix path with forward slashes (unchanged) "src/files/*.js" -> "src/files/*.js" ``` -------------------------------- ### Install cpx Source: https://github.com/mysticatea/cpx/blob/master/README.md Install the cpx module using npm. Requires Node.js version 6.5 or higher. ```bash npm install cpx ``` -------------------------------- ### Synchronous Copy with Options Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy-sync.md This example demonstrates using cpx.copySync() with multiple options to control the copy process, including preserving attributes, following symbolic links, and updating existing files. ```javascript cpx.copySync("src/**/*.css", "app", { preserve: true, dereference: true, update: true, }); console.log("Copy done with attributes preserved"); ``` -------------------------------- ### CLI Transform Resolution Examples Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/configuration.md Illustrates how to specify transforms using the CLI. Local files are resolved relative to the current directory, while other module names are resolved from `node_modules`. ```bash # Using a module from node_modules cpx "src/**/*.js" dist -t babelify # Using a local transform file cpx "src/**/*.js" dist -t ./transforms/custom.js ``` -------------------------------- ### CLI with Multiple Options Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/INDEX.md This command-line interface example demonstrates copying JavaScript files from 'src' to 'app' while watching for changes. It uses several options: `--watch` to enable continuous monitoring, `--clean` to remove existing files before copying, `--preserve` to maintain file attributes, and `--verbose` for detailed output. ```bash cpx "src/**/*.js" app --watch --clean --preserve --verbose ``` -------------------------------- ### Close Watcher on Demand Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/watcher.md Example of how to start watching files using cpx.watch and then stop watching after a specified delay using setTimeout and watcher.close(). ```javascript const watcher = cpx.watch("src/**/*", "dist"); watcher.on("watch-ready", () => { console.log("Watching..."); }); // Stop watching after 1 hour setTimeout(() => { watcher.close(); console.log("Watch stopped"); }, 3600000); ``` -------------------------------- ### Watch for Changes and Copy Files Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/configuration.md This example demonstrates how to use cpx to watch source files for changes and automatically copy them to the destination. The `--verbose` flag shows all file operations. ```bash cpx "src/**/*.{html,css,js}" app --watch --verbose ``` -------------------------------- ### Copy Assets on Build Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/INDEX.md This example demonstrates copying multiple asset types (HTML, CSS, images) from a source directory to a distribution directory using an asynchronous copy operation. A callback function handles potential errors and logs a success message. ```javascript const cpx = require("cpx"); cpx.copy("src/**/*.{html,css,png,jpg}", "dist", (err) => { if (err) throw err; console.log("Assets copied"); }); ``` -------------------------------- ### CLI Unknown Option Example Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/errors.md Demonstrates the cpx CLI behavior when an invalid option is provided. The CLI exits with code 1 and displays an 'Unknown option(s)' message. ```bash # Unknown option cpx src dest --invalid-flag # Exit code: 1 # Message: Unknown option(s): --invalid-flag ``` -------------------------------- ### Synchronous Copy Including Empty Directories Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy-sync.md This example shows how to use the 'includeEmptyDirs' option with cpx.copySync() to copy empty directories that are matched by the glob pattern, along with the 'update' option. ```javascript cpx.copySync("src/**/*", "output", { includeEmptyDirs: true, update: true, }); ``` -------------------------------- ### Verbose Output During Watch Mode Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/configuration.md This example shows how to enable verbose output while watching for changes. It's useful for monitoring all file copy and removal operations in real-time. ```bash cpx "src/**/*.html" public --watch --verbose ``` -------------------------------- ### Remove file with parent directory cleanup Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/remove-file-sync.md This example demonstrates removing a file and attempting to clean up its parent directory if it becomes empty. It specifically handles the case where the parent directory might not be empty. ```javascript // If "dist/utils/old-file.js" is the only file in "dist/utils" try { removeFileSync("dist/utils/old-file.js"); // Removes "dist/utils/old-file.js" // Also removes "dist/utils" (parent, if empty) console.log("Cleaned up"); } catch (err) { if (err.code === "ENOTEMPTY") { console.log("Parent dir has other files"); } else { console.error("Error:", err); } } ``` -------------------------------- ### CLI Missing Parameters Example Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/errors.md Illustrates the cpx CLI behavior when required parameters (source and destination) are missing. The CLI exits with code 1 and displays a help message. ```bash # Missing required parameters cpx src # Exit code: 1 # Displays help message ``` -------------------------------- ### Clean destination before copy Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy.md Use this example to clear the destination directory of files matching the source pattern before performing the copy operation. ```javascript cpx.copy("src/**/*.{html,css,js}", "dist", { clean: true, preserve: true, }).catch(err => { console.error("Failed:", err.message); }); ``` -------------------------------- ### Watcher 'watch-ready' Event Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/watcher.md Emitted when the watcher has completed its initial file copy and is ready to start observing file system changes. ```typescript watcher.on("watch-ready", () => { ... }) ``` -------------------------------- ### Watch with No Initial Copy Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/watch.md Configures the watcher to not perform an initial copy of files when it starts. It will only start watching for subsequent changes. ```javascript const watcher = cpx.watch("src/**/*.js", "dist", { initialCopy: false, }); watcher.on("watch-ready", () => { console.log("Ready to watch (no initial copy)"); }); ``` -------------------------------- ### Copy Files with Transformations Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/OVERVIEW.md Use this snippet to copy files while applying transformations, such as Babel transpilation and UglifyJS minification. Ensure the necessary transformation libraries are installed. ```javascript cpx.copy("src/**/*.js", "lib", { transform: [ (filepath) => require("babelify")(filepath, {...}), (filepath) => require("uglifyify")(filepath), ], }); ``` -------------------------------- ### Watch with Multiple Transforms Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/configuration.md Combine watching functionality with multiple file transformations. This example watches TypeScript files, transforms them with `typescript` and `uglifyify`, and copies them to the `lib` directory. ```bash cpx "src/**/*.ts" lib --transform typescript --transform uglifyify --watch ``` -------------------------------- ### Watch with Transformations Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/INDEX.md This example shows how to watch for JavaScript file changes in the 'src' directory and copy them to the 'lib' directory. It utilizes the `transform` option to apply Babel transformation to the files before copying, ensuring compatibility. ```javascript cpx.watch("src/**/*.js", "lib", { transform: [(filepath) => require("babelify")(filepath)], }) .on("copy", (e) => console.log("Copied:", e.srcPath)) .on("watch-error", (err) => console.error(err)); ``` -------------------------------- ### CLI Command Example with FILE Environment Variable Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/configuration.md Shows how to use the `--command` option with cpx to execute a shell command, utilizing the `$FILE` environment variable which represents the path of the file being transformed. ```bash cpx "src/**/*.js" dist --command "babel $FILE --out-file $FILE" ``` -------------------------------- ### Watcher.open() Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/watcher.md Starts the file watching process. This method initializes file system watchers and can trigger an initial copy operation if configured. It is typically called automatically when a Watcher instance is created via `cpx.watch()`. ```APIDOC ## open() ### Description Starts watching files. Sets up file system watchers and triggers initial copy if enabled. Called automatically when the Watcher is created by `cpx.watch()`. ### Method `open(): void` ### Example ```javascript const watcher = new Watcher(options); watcher.open(); ``` ``` -------------------------------- ### Watch with Options Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/watch.md Watch TypeScript files, copying them to dist. This example includes options to only copy if the destination is older, and to preserve file attributes. It also demonstrates listening for the 'copy' and 'watch-ready' events. ```typescript import * as cpx from 'cpx'; cpx.watch( 'src/**/*.ts', 'dist', { update: true, preserve: true } ).on('copy', ({ srcPath, dstPath }) => { console.log(`File ${srcPath} copied to ${dstPath}`); }).on('watch-ready', () => { console.log('Initial copy complete. Watching for changes...'); }); ``` -------------------------------- ### Synchronous Directory Copy Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy-file-sync.md Demonstrates copying a directory synchronously using copyFileSync. The function handles both files and directories. This example copies the contents of 'src/' to 'dist/' while preserving attributes. ```javascript // copyFileSync handles both files and directories copyFileSync("src/", "dist/", { preserve: true, update: false, }); ``` -------------------------------- ### cpx.watch Source: https://github.com/mysticatea/cpx/blob/master/README.md Copies files matching a source glob to a destination directory and then starts observing for changes, copying files whenever they are modified. Returns an EventEmitter. ```APIDOC ## cpx.watch ### Description Copy files that matches with `source` glob string to `dest` directory. After the first copy, starts observing. And copy the files when every changes. ### Method Signature ```ts cpx.watch(source, dest, options) cpx.watch(source, dest) ``` ### Parameters Arguments are the same as `cpx.copy`. `cpx.watch` returns an `EventEmitter` with the following events: - `.on("copy", (e) => { ... })` : Be fired after file is copied. `e.srcPath` is a path of original file. `e.dstPath` is a path of new file. - `.on("remove", (e) => { ... })` : Be fired after file is removed. `e.path` is a path of removed file. - `.on("watch-ready", () => { ... })` : Be fired when started watching files, after the first copying. - `.on("watch-error", (err) => { ... })` : Be fired when occurred errors during watching. ``` -------------------------------- ### Watch with Transforms and Clean Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/watch.md Watch CSS files, copying them to the build directory. This example uses the 'clean' option to remove existing files before the initial copy and includes a placeholder for a transform function to modify files during the copy process. ```typescript import * as cpx from 'cpx'; import * as path from 'path'; import * as ts from 'typescript'; // Example transform function (e.g., for CSS minification) const cssTransform = () => { // In a real scenario, this would be a transform stream // For demonstration, it just returns a passthrough stream return new (require('stream')).PassThrough(); }; cpx.watch( 'src/**/*.css', 'build', { clean: true, transform: [cssTransform] } ); ``` -------------------------------- ### applyAction() within Copy Implementation Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/apply-action.md Illustrates a typical usage pattern of applyAction() within a file copying implementation. This example uses a generator function and assumes `copyFile` and `toDestination` are defined elsewhere. ```javascript // From lib/copy.js - shows typical usage yield applyAction(options.source, options, sourcePath => { const outputPath = options.toDestination(sourcePath); if (outputPath !== sourcePath) { return copyFile(sourcePath, outputPath, options); } return Promise.resolve(); }); ``` -------------------------------- ### Copy current directory JS files Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/configuration.md This example demonstrates how to copy only the JavaScript files located directly within the 'src' directory (not subdirectories) to the 'dist' directory. ```bash cpx "src/*.js" dist ``` -------------------------------- ### Remove with Parent Cleanup Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/remove-file.md This example shows how to leverage the parent directory cleanup feature. If the target file is the last item in its parent directory, the parent directory will also be removed. It includes specific error handling for ENOTEMPTY. ```javascript // If "dist/utils/old-file.js" is the only file in "dist/utils" removeFile("dist/utils/old-file.js") // Removes "dist/utils/old-file.js" // Also removes "dist/utils" (parent, if empty) .then(() => console.log("Cleaned up")) .catch(err => { if (err.code === "ENOTEMPTY") { console.log("Parent dir has other files"); } }); ``` -------------------------------- ### Exclude Patterns Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/INDEX.md This example shows how to copy JavaScript and JSON files from 'src' to 'dist' while excluding specific patterns. The `dereference` option is enabled to follow symbolic links. The shell command equivalent is also provided. ```javascript cpx.copy("src/**/*.{js,json}", "dist", { dereference: true, }); // Shell: cpx "src/**/*.{js,json}" dist --dereference ``` -------------------------------- ### CLI Copy Failure Example Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/errors.md Shows a scenario where the cpx CLI might fail during a copy operation, particularly when used with watch mode and no initial copy. This results in an exit code of 1. ```bash # Copy failure cpx src dest --no-initial --watch & # (If copy fails) # Exit code: 1 ``` -------------------------------- ### CPX Common Options Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/INDEX.md Customize file copying behavior using these options. For example, `clean` removes existing files in the destination before copying, and `update` skips copying if the destination file is newer than the source. ```javascript { clean: false, // Remove matching files in dest before copy dereference: false, // Follow symbolic links includeEmptyDirs: false, // Copy empty directories initialCopy: true, // Copy before watching preserve: false, // Copy file attributes transform: [], // Stream transform factories update: false, // Skip if destination is newer } ``` -------------------------------- ### Basic normalizeOptions() Usage Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/normalize-options.md Demonstrates the basic usage of normalizeOptions() with source and output directory arguments. Shows the resulting NormalizedOptions object with default values. ```javascript const normalizeOptions = require("./lib/utils/normalize-options"); const opts = normalizeOptions("src/**/*.js", "dist"); // Returns: // { // baseDir: "src", // clean: false, // dereference: false, // includeEmptyDirs: false, // initialCopy: true, // outputDir: "dist", // preserve: false, // source: "src/**/*.js", // toDestination: [Function], // transform: [], // update: false // } ``` -------------------------------- ### applyAction() Basic Usage Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/apply-action.md Demonstrates basic usage of applyAction() with a simple logging action. Ensure the utility is correctly required. ```javascript const applyAction = require("./lib/utils/apply-action"); applyAction( "src/**/*.js", { includeEmptyDirs: false, dereference: false }, (sourcePath) => { console.log(`Processing: ${sourcePath}`); return Promise.resolve(); } ) .then(() => console.log("All files processed")) .catch(err => console.error("Error:", err)); ``` -------------------------------- ### Basic Path Normalization Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/normalize-path.md Demonstrates basic normalization of Windows-style and absolute paths. Ensure the utility is required before use. ```javascript const normalizePath = require("./lib/utils/normalize-path"); normalizePath("src\\files\\data.js"); // Returns: "src/files/data.js" normalizePath("/home/user/project/src/files"); // Returns: "src/files" (relative to cwd) ``` -------------------------------- ### applyActionSync Basic Usage Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/apply-action-sync.md Demonstrates basic usage of applyActionSync with a glob pattern and a simple console logging action. Ensure the utility is required correctly. ```javascript const applyActionSync = require("./lib/utils/apply-action-sync"); applyActionSync( "src/**/*.js", { includeEmptyDirs: false, dereference: false }, (sourcePath) => { console.log(`Processing: ${sourcePath}`); } ); console.log("All files processed"); ``` -------------------------------- ### Use removeFileSync in a clean operation Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/remove-file-sync.md This example shows how removeFileSync can be used within a larger operation, such as cleaning up files matching a pattern during a copy process. ```javascript // Used by copySync when files need to be cleaned const applyActionSync = require("./lib/utils/apply-action-sync"); applyActionSync(pattern, options, targetPath => { removeFileSync(targetPath); // Clean up matching files }); ``` -------------------------------- ### cpx.copy() - Basic Usage Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy.md Demonstrates the basic usage of cpx.copy() with a source glob pattern, destination directory, and an optional callback function for handling completion or errors. ```APIDOC ## cpx.copy() ### Description Asynchronously copy files matching a glob pattern to a destination directory. ### Method `cpx.copy(source, dest, callback)` ### Parameters #### Path Parameters - **source** (string) - Required - A file glob pattern to match source files (e.g., `"src/**/*.js"`) - **dest** (string) - Required - Destination directory path where matched files will be copied - **callback** (function) - Optional - Optional callback function of type `(err: Error\|null) => void` ### Request Example ```javascript const cpx = require("cpx"); cpx.copy("src/**/*.js", "dist", (err) => { if (err) { console.error("Copy failed:", err); } else { console.log("Copy completed"); } }); ``` ### Return Value A `Promise` that resolves when the copy operation completes. If a callback is provided, it is called with `(err)` upon completion and the promise is still returned. ``` -------------------------------- ### Watch with Clean Option Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/watch.md Sets up a watcher that cleans the destination directory before the initial copy and subsequent changes. Also preserves existing files in the destination. ```javascript const watcher = cpx.watch("src/**/*.{html,css}", "app", { clean: true, preserve: true, }); watcher.on("watch-ready", () => { console.log("Initial clean and copy complete, now watching"); }); watcher.on("watch-error", (err) => { console.error(err.message); process.exit(1); }); ``` -------------------------------- ### Catch Other Errors with try-catch Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/remove-file-sync.md For errors other than ENOENT and ENOTEMPTY (when applicable), removeFileSync throws exceptions that can be caught using a try-catch block. This example demonstrates catching permission-related errors. ```javascript try { removeFileSync("dist/protected.js"); } catch (err) { if (err.code === "EACCES") { console.error("Permission denied"); } else if (err.code === "EPERM") { console.error("Operation not permitted"); } else { console.error("Unexpected error:", err.code); } } ``` -------------------------------- ### applyAction() with File Operations Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/apply-action.md Shows how to use applyAction() to perform file operations, such as removing files, on matched files. Requires fs-extra for file system operations. ```javascript const applyAction = require("./lib/utils/apply-action"); const fs = require("fs-extra"); applyAction( "dist/**/*.js", { includeEmptyDirs: false, dereference: false }, (filepath) => { return fs.remove(filepath); } ) .then(() => console.log("All files removed")) .catch(err => console.error("Removal failed:", err)); ``` -------------------------------- ### Watch Without Initial Copy Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/configuration.md Configure cpx to watch for file changes without performing an initial copy of all files. This is useful when you only want to copy files as they are modified after the initial setup. ```bash cpx "src/**/*.js" dist --watch --no-initial ``` -------------------------------- ### Current Directory Glob Pattern Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/normalize-options.md Demonstrates the behavior of normalizeOptions() when a glob pattern matches files in the current directory (e.g., '*.js'). Shows that `baseDir` becomes '.' and how `toDestination` handles it. ```javascript const opts = normalizeOptions("*.js", "dist"); // baseDir is "." (current directory) // toDestination("file.js") returns "dist/file.js" ``` -------------------------------- ### Watch Files with Verbose Output Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/OVERVIEW.md This snippet demonstrates how to watch for file changes in a source directory and log specific events like copy, remove, and readiness. It's useful for real-time development feedback. ```javascript cpx.watch("src/**/*", "app") .on("copy", e => console.log(`Copied: ${e.srcPath}`)) .on("remove", e => console.log(`Removed: ${e.path}`)) .on("watch-ready", () => console.log("Watching...")) .on("watch-error", err => console.error(err)); ``` -------------------------------- ### applyAction() Glob Options Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/apply-action.md Configuration options passed to the underlying glob.Glob instance. These options control directory inclusion, symlink following, and sorting. ```javascript { nodir: !options.includeEmptyDirs, silent: true, follow: Boolean(options.dereference), nosort: true, } ``` -------------------------------- ### cpx.copy() - Using Promises Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy.md Illustrates how to use cpx.copy() with Promises for asynchronous operations, allowing for cleaner chaining of operations and error handling. ```APIDOC ## cpx.copy() with Promises ### Description Use cpx.copy() with Promises for asynchronous file copying. ### Method `cpx.copy(source, dest)` ### Parameters #### Path Parameters - **source** (string) - Required - A file glob pattern to match source files (e.g., `"src/**/*.html"`) - **dest** (string) - Required - Destination directory path where matched files will be copied ### Request Example ```javascript cpx.copy("src/**/*.html", "build") .then(() => console.log("Copy done")) .catch(err => console.error(err)); ``` ### Return Value A `Promise` that resolves when the copy operation completes. ``` -------------------------------- ### Basic Synchronous Copy with cpx.copySync() Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy-sync.md Use this to perform a basic synchronous file copy operation. It requires importing the 'cpx' module and handling potential errors with a try-catch block. ```javascript const cpx = require("cpx"); try { cpx.copySync("src/**/*.js", "dist"); console.log("Copy completed"); } catch (err) { console.error("Copy failed:", err); } ``` -------------------------------- ### CPX Watch Events Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/INDEX.md Handle file system events during watch operations. Events like 'copy' and 'remove' provide details about the affected files, while 'watch-ready' indicates the watcher has started, and 'watch-error' reports any errors. ```javascript watcher .on("copy", (e) => {...}) // { srcPath, dstPath } .on("remove", (e) => {...}) // { path } .on("watch-ready", () => {...}) // Watching started .on("watch-error", (err) => {...}) // Watch error ``` -------------------------------- ### normalizeOptions() with Custom Options Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/normalize-options.md Illustrates how to use normalizeOptions() with a custom options object to override default settings like clean, preserve, and update. ```javascript const opts = normalizeOptions( "src/**/*.css", "app", { clean: true, preserve: true, update: true, } ); // Returns normalized options with clean, preserve, update set to true ``` -------------------------------- ### applyActionSync with File Operations Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/apply-action-sync.md Shows how to use applyActionSync to perform file system operations, such as removing files, on matched files. Requires fs-extra for synchronous file removal. ```javascript const applyActionSync = require("./lib/utils/apply-action-sync"); const fs = require("fs-extra"); applyActionSync( "dist/**/*.js", { includeEmptyDirs: false, dereference: false }, (filepath) => { fs.removeSync(filepath); } ); console.log("All files removed"); ``` -------------------------------- ### Copy with Transformations Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/OVERVIEW.md Copies JavaScript files from 'src' to 'lib', applying Babel transformations using 'babelify' and executing with 'babel-node'. ```bash cpx "src/**/*.js" lib --transform babelify --command "babel-node" ``` -------------------------------- ### cpx.copy() - With Options Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy.md Shows how to use cpx.copy() with an options object to customize the copy behavior, including options like `preserve`, `dereference`, and `update`. ```APIDOC ## cpx.copy() with Options ### Description Customize file copying behavior using the `options` object. ### Method `cpx.copy(source, dest, options)` ### Parameters #### Path Parameters - **source** (string) - Required - A file glob pattern to match source files (e.g., `"src/**/*.css"`) - **dest** (string) - Required - Destination directory path where matched files will be copied - **options** (object) - Optional - Configuration object with copy behavior flags - **preserve** (boolean) - Optional - Copy file attributes: uid, gid, atime, and mtime - **dereference** (boolean) - Optional - Follow symbolic links when copying from them - **update** (boolean) - Optional - Do not overwrite destination files if they are newer than source files ### Request Example ```javascript cpx.copy("src/**/*.css", "app", { preserve: true, dereference: true, update: true, }).then(() => console.log("Copied with attributes preserved")); ``` ### Return Value A `Promise` that resolves when the copy operation completes. ``` -------------------------------- ### Combine CPX with Browserify and Watchify Source: https://github.com/mysticatea/cpx/blob/master/README.md Integrates CPX file copying with Browserify for JavaScript bundling and Watchify for live-reloading. This command copies files and then runs watchify. ```bash $ cpx "src/**/*.{html,png,jpg}" app -w & watchify src/index.js -o app/index.js ``` -------------------------------- ### CPX CLI with Transform Packages Source: https://github.com/mysticatea/cpx/blob/master/README.md Copies JavaScript files and applies specified transform packages (e.g., Babelify, Uglifyify) during the copy process. Use the `-t` flag for each transform package. ```bash $ cpx "src/**/*.js" app -w -t babelify -t uglifyify ``` -------------------------------- ### Copy with transform streams Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy.md This snippet shows how to apply transformations, such as Babel transpilation, to files during the copy process. ```javascript const babel = require("babelify"); cpx.copy("src/**/*.js", "lib", { transform: [babel.configure()], }).then(() => console.log("Babel transformed")); ``` -------------------------------- ### toDestination Function Behavior Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/normalize-options.md Explains the behavior of the `toDestination` function generated by normalizeOptions(). It shows how source paths are transformed into destination paths by replacing the base directory. ```javascript const opts = normalizeOptions("src/**/*.js", "lib"); // For a source file: const destPath = opts.toDestination("src/utils/helper.js"); // Returns: "lib/utils/helper.js" // The "src" base is replaced with "lib" // For the base directory itself: const baseDest = opts.toDestination("src"); // May return "src" (not transformed) if matching the source ``` -------------------------------- ### Basic File Copy with Glob Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/OVERVIEW.md Copies all JavaScript files from the 'src' directory recursively to the 'dist' directory. ```bash cpx "src/**/*.js" dist ``` -------------------------------- ### Watch for File Changes Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/OVERVIEW.md Copies all files from 'src' to 'app' and watches for any changes, providing verbose output. ```bash cpx "src/**/*" app --watch --verbose ``` -------------------------------- ### Directory copy Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy-file-sync.md Demonstrates that `copyFileSync` can also be used to copy directories recursively. ```APIDOC ## Directory copy ### Description The `copyFileSync` function is versatile and can handle copying directories as well as files. This example shows copying a directory structure. ### Code Example ```javascript // copyFileSync handles both files and directories copyFileSync("src/", "dist/", { preserve: true, update: false, }); ``` ``` -------------------------------- ### Copy using Promise Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy.md This snippet demonstrates using the Promise-based API for copying files, which is useful for chaining asynchronous operations. ```javascript cpx.copy("src/**/*.html", "build") .then(() => console.log("Copy done")) .catch(err => console.error(err)); ``` -------------------------------- ### Remove a Directory Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/remove-file.md This snippet demonstrates how to remove a directory using the removeFile utility. It also includes basic promise handling. ```javascript removeFile("dist/old-folder") .then(() => console.log("Directory removed")) .catch(err => console.error("Failed to remove:", err)); ``` -------------------------------- ### Basic copy with callback Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy.md Use this snippet for a basic file copy operation when a callback is preferred for handling completion or errors. ```javascript const cpx = require("cpx"); cpx.copy("src/**/*.js", "dist", (err) => { if (err) { console.error("Copy failed:", err); } else { console.log("Copy completed"); } }); ``` -------------------------------- ### Absolute to Relative Path Conversion Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/normalize-path.md Demonstrates the conversion of absolute paths to relative paths based on the current working directory (cwd). Assumes a cwd of '/home/user/project'. ```javascript // Assuming cwd is /home/user/project normalizePath("/home/user/project/src"); // Returns: "src" normalizePath("/home/user/project"); // Returns: "." ``` -------------------------------- ### Basic File Copy Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/OVERVIEW.md Use this snippet to copy files from a source pattern to a destination directory. It handles errors by throwing them. ```javascript const cpx = require("cpx"); cpx.copy("src/**/*.js", "dist", (err) => { if (err) throw err; console.log("Copy complete"); }); ``` -------------------------------- ### Instantiate Watcher Directly Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/watcher.md Advanced usage for directly instantiating the Watcher class. Requires normalizing options first. Listen for 'copy' and 'watch-error' events. ```javascript const normalizeOptions = require("./lib/utils/normalize-options"); const Watcher = require("./lib/utils/watcher"); const options = normalizeOptions("src/**/*.js", "dist", { preserve: true, }); const watcher = new Watcher(options); watcher.on("copy", (e) => { console.log(`Copied: ${e.srcPath} -> ${e.dstPath}`); }); watcher.on("watch-error", (err) => { console.error(`Error: ${err.message}`); }); watcher.open(); ``` -------------------------------- ### CPX Main Functions Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/INDEX.md Use these functions for asynchronous or synchronous file copying and for watching file changes. The callback function in `cpx.copy` is invoked upon completion or error. ```javascript const cpx = require("cpx"); // Async copy cpx.copy(source, dest, options?, callback?) // Sync copy cpx.copySync(source, dest, options?) // Watch and copy cpx.watch(source, dest, options?) ``` -------------------------------- ### applyActionSync Inside copySync Implementation Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/apply-action-sync.md Illustrates a typical internal usage pattern of applyActionSync within the context of a copySync implementation, showing how to map source paths to destination paths and conditionally copy files. ```javascript // From lib/copy-sync.js - shows typical usage applyActionSync(options.source, options, sourcePath => { const outputPath = options.toDestination(sourcePath) if (outputPath !== sourcePath) { copyFileSync(sourcePath, outputPath, options) } }); ``` -------------------------------- ### cpx CLI Usage Source: https://github.com/mysticatea/cpx/blob/master/README.md Basic command-line usage for cpx. Specify source glob and destination path. Supports various options for copying and watching. ```bash Usage: cpx [options] Copy files, watching for changes. The glob of target files. The path of a destination directory. Options: -c, --command A command text to transform each file. -C, --clean Clean files that matches like pattern in directory before the first copying. -L, --dereference Follow symbolic links when copying from them. -h, --help Print usage information. --include-empty-dirs The flag to copy empty directories which is matched with the glob. --no-initial The flag to not copy at the initial time of watch. Use together '--watch' option. -p, --preserve The flag to copy attributes of files. This attributes are uid, gid, atime, and mtime. -t, --transform A module name to transform each file. cpx lookups the specified name via "require()". -u, --update The flag to not overwrite files on destination if the source file is older. -v, --verbose Print copied/removed files. -V, --version Print the version number. -w, --watch Watch for files that matches , and copy the file to every changing. ``` -------------------------------- ### Copy File or Directory Synchronously Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy-file-sync.md Use this snippet to copy a file or directory synchronously. It ensures the output directory exists before copying. ```javascript fs.ensureDirSync(path.dirname(output)) fs.copySync(source, output) ``` -------------------------------- ### With attribute preservation Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy-file-sync.md Illustrates copying a file while preserving its original attributes like ownership and timestamps. ```APIDOC ## With attribute preservation ### Description This example demonstrates copying a file and preserving its attributes (uid, gid, atime, mtime) by setting the `preserve` option to `true`. ### Code Example ```javascript copyFileSync("src/important.js", "dist/important.js", { preserve: true, // Copy uid, gid, atime, mtime update: false, }); console.log("File copied with attributes"); ``` ``` -------------------------------- ### Handle Missing Files Gracefully Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/remove-file.md This snippet illustrates how removeFile handles non-existent files. The promise will resolve successfully even if the target path does not exist, preventing unexpected rejections. ```javascript removeFile("dist/nonexistent.js") .then(() => console.log("File removed (or already gone)")) // Does not reject even if file doesn't exist .catch(err => console.error("Unexpected error:", err)); ``` -------------------------------- ### cpx.copy() - Clean Before Copy Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy.md Explains how to use the `clean` option in cpx.copy() to remove files in the destination directory that match the source pattern before performing the copy operation. ```APIDOC ## cpx.copy() - Clean Before Copy ### Description Remove files in the destination directory that match the source pattern before copying. ### Method `cpx.copy(source, dest, options)` ### Parameters #### Path Parameters - **source** (string) - Required - A file glob pattern to match source files (e.g., `"src/**/*.{html,css,js}"`) - **dest** (string) - Required - Destination directory path where matched files will be copied - **options** (object) - Optional - Configuration object with copy behavior flags - **clean** (boolean) - Optional - Remove files in destination that match the source pattern before copying - **preserve** (boolean) - Optional - Copy file attributes: uid, gid, atime, and mtime ### Request Example ```javascript cpx.copy("src/**/*.{html,css,js}", "dist", { clean: true, preserve: true, }).catch(err => { console.error("Failed:", err.message); }); ``` ### Return Value A `Promise` that resolves when the copy operation completes. ``` -------------------------------- ### copyFileSync() Signature Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy-file-sync.md Synchronously copies a file from a source path to an output path, with optional configuration for preserving attributes and updating existing files. ```APIDOC ## copyFileSync() ### Description Synchronously copies a single file from a source path to an output path. It can optionally preserve file attributes and update the destination if it's newer than the source. ### Method Signature ```typescript function copyFileSync( source: string, output: string, options: object ): void ``` ### Parameters #### Path Parameters - **source** (string) - Required - Path to the source file to copy. - **output** (string) - Required - Path to the destination file. #### Request Body - **options** (object) - Required - Options object with copy behavior. - **preserve** (boolean) - Optional - Copy file attributes (uid, gid, atime, mtime). - **update** (boolean) - Optional - Skip copy if destination is newer than source. ``` -------------------------------- ### Basic synchronous copy Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy-file-sync.md Demonstrates a basic synchronous file copy operation without preserving attributes or updating the destination if it's newer. ```APIDOC ## Basic synchronous copy ### Description This example shows how to use `copyFileSync` for a straightforward file copy. It sets `preserve` and `update` options to `false`. ### Code Example ```javascript const copyFileSync = require("./lib/utils/copy-file-sync"); try { copyFileSync("src/file.js", "dist/file.js", { preserve: false, update: false, }); console.log("File copied"); } catch (err) { console.error("Copy failed:", err); } ``` ``` -------------------------------- ### cpx.copy() - With Transform Streams Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/copy.md Demonstrates using transform streams with cpx.copy() to modify file content during the copy process, such as applying Babel transformations. ```APIDOC ## cpx.copy() with Transform Streams ### Description Apply transformations to file content during the copy process using transform streams. ### Method `cpx.copy(source, dest, options)` ### Parameters #### Path Parameters - **source** (string) - Required - A file glob pattern to match source files (e.g., `"src/**/*.js"`) - **dest** (string) - Required - Destination directory path where matched files will be copied - **options** (object) - Optional - Configuration object with copy behavior flags - **transform** (function[]) - Optional - Array of transform stream factory functions; each receives `(filepath, options)` and returns a stream.Transform object ### Request Example ```javascript const babel = require("babelify"); cpx.copy("src/**/*.js", "lib", { transform: [babel.configure()], }).then(() => console.log("Babel transformed")); ``` ### Return Value A `Promise` that resolves when the copy operation completes. ``` -------------------------------- ### Glob Options for applyActionSync Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/apply-action-sync.md Details the glob.sync options that are internally used by applyActionSync, derived from the provided options object. These control directory inclusion and symbolic link following. ```javascript { nodir: !options.includeEmptyDirs, silent: true, follow: Boolean(options.dereference), } ``` -------------------------------- ### CPX CLI with Custom Command Transformation Source: https://github.com/mysticatea/cpx/blob/master/README.md Copies JavaScript files and applies a custom shell command (e.g., Babel) for transformation during the copy process. The `-c` flag specifies the command to execute. ```bash $ cpx "src/**/*.js" app -w -c "babel --source-maps inline" ``` -------------------------------- ### Remove a directory synchronously Source: https://github.com/mysticatea/cpx/blob/master/_autodocs/api-reference/remove-file-sync.md Use this to synchronously remove a directory. It will throw an error if the removal fails for reasons other than the directory not existing. ```javascript try { removeFileSync("dist/old-folder"); console.log("Directory removed"); } catch (err) { console.error("Failed to remove:", err); } ```