copy-dir vs copyfiles vs cpx vs fs-extra vs ncp vs rimraf
File and Directory Copying Utilities in Node.js Build Toolchains
copy-dircopyfilescpxfs-extrancprimrafSimilar Packages:

File and Directory Copying Utilities in Node.js Build Toolchains

copy-dir, copyfiles, cpx, fs-extra, ncp, and rimraf are Node.js packages commonly used in frontend build pipelines to handle file system operations—particularly copying, moving, or cleaning files and directories. While some focus exclusively on copying (like copyfiles and cpx), others offer broader utilities (fs-extra) or specialize in deletion (rimraf). These tools integrate into scripts for asset bundling, static site generation, or deployment preparation, often invoked via npm scripts or task runners.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
copy-dir0---6 years agoMIT
copyfiles0422-566 years agoMIT
cpx0527-3510 years agoMIT
fs-extra09,60658.6 kB1417 days agoMIT
ncp0682-7811 years agoMIT
rimraf05,850262 kB95 months agoBlueOak-1.0.0

File and Directory Operations in Frontend Build Pipelines: A Practical Comparison

Frontend developers routinely need to copy assets, clean output folders, or sync static files during builds. The packages copy-dir, copyfiles, cpx, fs-extra, ncp, and rimraf each solve parts of this puzzle—but with very different scopes, APIs, and trade-offs. Let’s break down how they work in real-world scenarios.

📁 Core Capabilities: What Each Package Actually Does

copy-dir copies entire directories recursively—but synchronously and without options.

// copy-dir: sync only, no globs
const copydir = require('copy-dir');
copydir.sync('src/assets', 'dist/assets');

copyfiles focuses on copying files via glob patterns while maintaining relative paths.

# copyfiles: CLI with glob support
npx copyfiles -u 1 "src/**/*.{png,jpg}" dist/

cpx provides async copying with globbing, watch mode, and promise support.

# cpx: CLI with watch
npx cpx "public/**/*" dist/ --watch
// cpx: programmatic usage
const cpx = require("cpx");
cpx.copy("src/images/*.svg", "dist/img", { preserve: true });

fs-extra is a full filesystem toolkit including copy(), move(), remove(), and more.

// fs-extra: robust programmatic copy
const { copy } = require('fs-extra');
await copy('src/static', 'dist/static', { overwrite: true });

ncp was an early async recursive copier—but is now deprecated.

// ncp: DO NOT USE in new code
const ncp = require('ncp');
ncp('old/', 'new/', err => { /* ... */ }); // Unmaintained!

rimraf deletes directories recursively—nothing more.

// rimraf: safe rm -rf
const rimraf = require('rimraf');
rimraf.sync('dist');
# Often used in npm scripts
"clean": "rimraf dist"

🔍 Filtering and Glob Support: Precision Matters

When copying assets, you rarely want everything. How do these tools handle selective copying?

copyfiles excels here with intuitive glob-to-structure mapping:

# Copies src/components/Button/icon.png → dist/components/Button/icon.png
npx copyfiles -u 2 "src/components/**/icon.png" dist/

cpx supports standard globs and exclusion patterns:

npx cpx "src/assets/**/*.{png,jpg}" "!src/assets/old/**" dist/assets/

fs-extra.copy() does not support globs—you must resolve paths yourself:

const { glob } = require('glob');
const { copy } = require('fs-extra');
const files = await glob('src/**/*.svg');
for (const file of files) {
  const dest = file.replace('src', 'dist');
  await copy(file, dest);
}

copy-dir and ncp offer no built-in filtering—you copy entire trees or nothing.

⚙️ Programmatic vs CLI Usage

Some tools are designed for shell scripts; others for JavaScript logic.

  • CLI-optimized: copyfiles, cpx, and rimraf work seamlessly in package.json scripts:

    {
      "scripts": {
        "build": "rimraf dist && copyfiles -u 1 "src/public/**" dist && tsc"
      }
    }
    
  • Programmatic-first: fs-extra integrates naturally into custom build tools or Gulp-like pipelines:

    // In a custom builder
    await fs.emptyDir('dist');
    await fs.copy('src/html', 'dist');
    await bundleJS();
    
  • Hybrid: cpx offers both CLI and API, but its programmatic interface is less feature-rich than fs-extra.

🧹 Cleanup Workflows: Why rimraf Stands Alone

None of the copying tools handle deletion well—except rimraf, which does only that, and does it reliably across platforms:

// Windows-safe recursive delete
const rimraf = require('rimraf');
rimraf('node_modules/.cache', () => console.log('Cleaned'));

Trying to delete with fs-extra.remove() works too, but rimraf remains the de facto standard in frontend tooling due to its simplicity and legacy adoption.

⚠️ Critical Caveats and Deprecations

  • ncp is deprecated. Its npm page states: "This module is no longer maintained." Use fs-extra.copy() instead.
  • copy-dir is synchronous only. This blocks the event loop—unacceptable in larger projects or CI environments.
  • fs-extra.copy() follows symlinks by default, which may cause infinite loops. Use { dereference: false } if needed.
  • cpx and copyfiles don’t remove stale files. If you delete src/image.png, the old dist/image.png remains—consider pairing with a clean step.

💡 Real-World Recommendation Patterns

For simple npm script workflows:

{
  "scripts": {
    "clean": "rimraf dist",
    "copy:assets": "copyfiles -u 1 "src/public/**/*" dist",
    "build": "npm run clean && npm run copy:assets && rollup -c"
  }
}

→ Use rimraf + copyfiles

For programmatic build tools (e.g., custom bundler plugins):

await fs.emptyDir(outDir);
await fs.copy(path.resolve(__dirname, 'static'), path.join(outDir, 'static'));

→ Use fs-extra

For dev-time asset watching:

npx cpx "src/assets/**" dist/assets --watch

→ Use cpx

✅ Summary: When to Reach for Which Tool

TaskBest ChoiceWhy
Recursive directory copy (sync)copy-dirOnly if you control inputs and sync is acceptable
Glob-based file copyingcopyfilesSimple, CLI-friendly, preserves structure
Watch-mode asset synccpxBuilt-in watch, modern glob support
Full filesystem operationsfs-extraReliable, promise-based, handles edge cases
Recursive deletionrimrafIndustry standard for rm -rf in JS
Legacy async copyAvoid ncpDeprecated—migrate to fs-extra

Choose based on whether your workflow lives in shell scripts or JavaScript—and whether you need just copying, or a full suite of filesystem utilities.

How to Choose: copy-dir vs copyfiles vs cpx vs fs-extra vs ncp vs rimraf

  • copy-dir:

    Choose copy-dir if you need a minimal, synchronous utility strictly for recursive directory copying with no dependencies. It’s useful in simple CLI scripts where async behavior isn’t required and you control the source/target structure tightly. However, it lacks filtering, glob support, or error resilience, making it unsuitable for complex or production-grade workflows.

  • copyfiles:

    Choose copyfiles when your primary need is to copy files matching glob patterns while preserving directory structure relative to a base path. It shines in build scripts that move compiled assets (e.g., CSS, images) from src to dist. Its CLI-first design integrates cleanly with npm scripts but offers limited programmatic control or advanced options like transform hooks.

  • cpx:

    Choose cpx if you want a modern, promise-based copier with strong glob support, watch mode, and clean CLI ergonomics. It’s ideal for development workflows requiring live asset syncing (e.g., copying SVGs during dev server reloads). However, it doesn’t handle directory removal or non-copy filesystem tasks, so pair it with other tools for full pipeline coverage.

  • fs-extra:

    Choose fs-extra when you need a robust, general-purpose filesystem toolkit that includes recursive copy (copy()), move, ensureDir, and more—all with Promise support and graceful error handling. It’s the go-to for programmatic build logic in custom scripts or tooling where reliability and flexibility outweigh minimalism. Avoid it only if you strictly need a CLI-only solution with zero runtime dependencies.

  • ncp:

    Do not choose ncp for new projects—it is officially deprecated and unmaintained. While it once provided async recursive copying with basic filtering, its lack of updates means unresolved bugs and missing modern Node.js compatibility. Migrate existing usage to fs-extra.copy() or cpx depending on whether you need programmatic control or CLI convenience.

  • rimraf:

    Choose rimraf exclusively when your task is recursive directory deletion (the Unix rm -rf equivalent). It has no copying capabilities but is often paired with copiers in build scripts (e.g., clean dist before copying assets). Its battle-tested implementation handles Windows path quirks reliably, making it a standard dependency in frontend toolchains for cleanup steps.

README for copy-dir

copy-dir

Easy used 'copy-dir' lib, even use a filter, copy a file or directory to another path, when target path or parent target path not exists, it will create the directory automatically.

install

npm install copy-dir

grammar

Sync Mode:

copydir.sync(from, to[, options]);

Async Mode:

copydir(from, to, [options, ]callback);

[options]:

  utimes: false,  // Boolean | Object, keep addTime or modifyTime if true
  mode: false,    // Boolean | Number, keep file mode if true
  cover: true,    // Boolean, cover if file exists
  filter: true,   // Boolean | Function, file filter

filter is a function that you want to filter the path, then return true or false.

It can use three arguments named state, filepath, filename

  • state: String, 'file' / 'directory' / 'symbolicLink', marked as the file or path type
  • filepath: String, the file path
  • filename: String, the file name

usage

Sync Mode:

var copydir = require('copy-dir');

copydir.sync('/my/from/path', '/my/target/path', {
  utimes: true,  // keep add time and modify time
  mode: true,    // keep file mode
  cover: true    // cover file when exists, default is true
});

Async Mode:

var copydir = require('copy-dir');

copydir('/my/from/path', '/my/target/path', {
  utimes: true,  // keep add time and modify time
  mode: true,    // keep file mode
  cover: true    // cover file when exists, default is true
}, function(err){
  if(err) throw err;
  console.log('done');
});

add a filter

When you want to copy a directory, but some file or sub directory is not you want, you can do like this:

Sync Mode:

var path = require('path');
var copydir = require('copy-dir');

copydir.sync('/my/from/path', '/my/target/path', {
  filter: function(stat, filepath, filename){
    // do not want copy .html files
    if(stat === 'file' && path.extname(filepath) === '.html') {
      return false;
    }
    // do not want copy .svn directories
    if (stat === 'directory' && filename === '.svn') {
      return false;
    }
    // do not want copy symbolicLink directories
    if (stat === 'symbolicLink') {
      return false;
    }
    return true;  // remind to return a true value when file check passed.
  }
});
console.log('done');

Async Mode:

var path = require('path');
var copydir = require('copy-dir');

copydir('/a/b/c', '/a/b/e', {
  filter: function(stat, filepath, filename) {
    //...
    return true;
  }
}, function(err) {
  //...
});

Update Logs

1.3.0

Bug fix: filter function arguments incorrect, delete the third argument: dirname

Questions?

If you have any questions, please feel free to ask through New Issue.

License

copy-dir is available under the terms of the MIT License.