Copy files

Related tags

Command Line cpy
Overview

cpy

Copy files

Why

  • Fast by using streams.
  • Resilient by using graceful-fs.
  • User-friendly by accepting globs and creating non-existent destination directories.
  • User-friendly error messages.
  • Progress reporting.

Install

$ npm install cpy

Usage

const cpy = require('cpy');

(async () => {
	await cpy(['source/*.png', '!source/goat.png'], 'destination');
	console.log('Files copied!');
})();

API

cpy(source, destination, options?)

Returns a Promise<string[]> with the destination file paths.

source

Type: string | string[]

Files to copy.

If any of the files do not exist, an error will be thrown (does not apply to globs).

destination

Type: string

Destination directory.

options

Type: object

Options are passed to globby.

In addition, you can specify the below options.

cwd

Type: string
Default: process.cwd()

Working directory to find source files.

overwrite

Type: boolean
Default: true

Overwrite existing files.

parents

Type: boolean
Default: false

Preserve path structure.

rename

Type: string | Function

Filename or function returning a filename used to rename every file in source.

const cpy = require('cpy');

(async () => {
	await cpy('foo.js', 'destination', {
		rename: basename => `prefix-${basename}`
	});
})();
concurrency

Type: number
Default: (os.cpus().length || 1) * 2

Number of files being copied concurrently.

ignoreJunk

Type: boolean
Default: true

Ignores junk files.

filter

Type: Function

Function to filter files to copy.

Receives a source file object as the first argument.

Return true to include, false to exclude. You can also return a Promise that resolves to true or false.

const cpy = require('cpy');

(async () => {
	await cpy('foo', 'destination', {
		filter: file => file.extension !== 'nocopy'
	});
})();
Source file object
path

Type: string
Example: '/tmp/dir/foo.js'

Resolved path to the file.

relativePath

Type: string
Example: 'dir/foo.js' if cwd was '/tmp'

Relative path to the file from cwd.

name

Type: string
Example: 'foo.js'

Filename with extension.

nameWithoutExtension

Type: string
Example: 'foo'

Filename without extension.

extension

Type: string
Example: 'js'

File extension.

Progress reporting

cpy.on('progress', handler)

handler(progress)

Type: Function

progress
{
	completedFiles: number,
	totalFiles: number,
	completedSize: number,
	percent: number
}
  • completedSize is in bytes
  • percent is a value between 0 and 1

Note that the .on() method is available only right after the initial cpy call, so make sure you add a handler before awaiting the promise:

(async () => {
	await cpy(source, destination).on('progress', progress => {
		// …
	});
})();

Related

Comments
  • Progress reporting

    Progress reporting

    It would be nice to have an ability to hook into underlying stream(s) to have this. This might be more tricky to get right WRT multiple files, though. Opening issue first to discuss.

    enhancement help wanted 
    opened by YurySolovyov 39
  • Implement recursive and flat copy

    Implement recursive and flat copy

    Fixes #61 Fixes #84 Fixes #60

    • [ ] optimize and refactor
    • [x] update docs
    • [x] add better typescript types
    • [x] write more tests
    • [x] handle rename option
    • [x] copying folders structure
    • [x] flattening file structure
    • [x] current tests passing on windows
    • [x] current tests passing on linux

    Examples:

    cpy('node_modules', 'web_modules') outputs web_modules/node_modules/module1 node_modules files are copied recursively and structure is preserved.

    cpy('node_modules/**', 'web_modules') outputs web_modules/module1 node_modules files are copied recursively and structure is preserved. Only node_modules content will be copied to web_modules.

    cpy('node_modules/**', 'web_modules', {flat: true}) outputs web_modules/file1 node_modules files are copied recursively and structure is not preserved. Only node_modules content will be copied to web_modules.

    cpy('node_modules/**/*.cmd', 'web_modules') will recreate node_modules structure but all non cmd files will be ommited


    IssueHunt Summary

    Referenced issues

    This pull request has been submitted to:


    opened by Idered 34
  • Add `filter` option

    Add `filter` option

    • Add filter option

    Fixes #63


    IssueHunt Summary

    Referenced issues

    This pull request has been submitted to:


    IssueHunt has been backed by the following sponsors. Become a sponsor

    opened by stroncium 15
  • Source paths always preserved

    Source paths always preserved

    Is this expected behavior for the CLI?

    (at root of module)

    flet@lappy:~/code/someproject$ ls assets/markup/
    mock.html
    
    flet@lappy:~/code/someproject$ cpy assets/markup/*.html dist
    
    flet@lappy:~/code/someproject$ tree dist
    dist
    └── assets
        └── markup
            └── mock.html
    
    

    I guess I was expecting it to work similarly to cp in linux?

    flet@lappy:~/code/someproject$ cp assets/markup/*.html dist
    
    flet@lappy:~/code/someproject$ tree dist
    dist
    └── mock.html
    

    I realize this might not be the goal of this module and I'm prepared for this issue to be closed immediately :)

    opened by Flet 12
  • Copy separate file, with possible new name

    Copy separate file, with possible new name

    I'd like to copy an existing file to a new path, with a possible new name. The idea would be something like

    cpy package.json Build/$npm_package_name-$npm_package_version.json
    

    I think we would need an option for that. Or we could check for a trailing slash, like cp does. I would prefer the later one, I'm not sure if that's a good idea because it might break existing use cases.

    opened by tobiastom 11
  • Copy in serial?

    Copy in serial?

    It seems really unlikely to me that copying a bunch of files in parallel would speed anything up. Indeed, I would not be surprised to find it slowed things down. Increasing the number of files read simultaneously seems likely to encourage lots of seek delays for HDD's, and SSD's should be able to saturate their bandwidth regardless of how many files are being copied simultaneously.

    It's probably worth running some benchmarks to prove this, but I think you would have seen Operating Systems commands / GUI's doing parallel copies if there were any advantage to it.

    I guess technically, you could be copying from multiple slow network mounted drives - in which case parallelization might make sense. But I think that's a very small (possibly non-existent) percentage of users.

    enhancement help wanted 
    opened by jamestalmage 10
  • simplify API for --parents option

    simplify API for --parents option

    Hi,

    If I want to copy all the html in assets directory and keep the directory structure inside dist directory I have to do the following command :

    cpy '**/*.html' '../dist/' --cwd=assets --parents
    

    I think the following command would be easier :

    cpy 'assets/**/*.html' dist --parents
    
    assets
    ├── index.html
    ├── robots.txt
    └── test
        └── test.html
    

    should return

    dist
    ├── index.html
    └── test
        └── test.html
    

    not

    dist
    └── assets
        ├── index.html
        └── test
            └── test.html
    
    npm -v
    2.14.7
    
    node -v
    4.2.3
    
    uname -a
    Linux guillaume-x240 3.19.0-39-generic #44~14.04.1-Ubuntu SMP Wed Dec 2 10:00:35 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
    

    here the red test https://github.com/guillaumevincent/cpy/commit/fad2b31882100ef914cc570cb84e8fd66b0197cf

    opened by guillaumevincent 10
  • cpy has transitive dependencies with a CVE vulnerability

    cpy has transitive dependencies with a CVE vulnerability

    cpy depends on globby @ ^12.0.2. Following the dependency chain, this also pulls in globby @ 9.2.0. That version of globby depends on fast-glob which depends on glob-parent at a specific version with a vulnerability.

    | +-- [email protected]
    | | +-- @types/[email protected]
    | | | +-- @types/[email protected]
    | | | `-- @types/[email protected]
    | | +-- [email protected]
    | | | `-- [email protected]
    | | +-- [email protected]
    | | | `-- [email protected]
    | | |   `-- [email protected]
    | | +-- [email protected]
    | | | +-- @mrmlnc/[email protected]
    | | | | +-- [email protected]
    | | | | `-- [email protected]
    | | | +-- @nodelib/[email protected]
    | | | +-- [email protected] <---
    | | | | +-- [email protected]
    | | | | | `-- [email protected] deduped
    | | | | `-- [email protected]
    
    +-------------+------------------+----------+-------------------+---------------+---------------------------------------+
    |   LIBRARY   | VULNERABILITY ID | SEVERITY | INSTALLED VERSION | FIXED VERSION |                 TITLE                 |
    +-------------+------------------+----------+-------------------+---------------+---------------------------------------+
    | glob-parent | CVE-2020-28469   | HIGH     | 3.1.0             | 5.1.2         | nodejs-glob-parent: Regular           |
    |             |                  |          |                   |               | expression denial of service          |
    |             |                  |          |                   |               | -->avd.aquasec.com/nvd/cve-2020-28469 |
    +-------------+------------------+----------+-------------------+---------------+---------------------------------------+
    

    The latest version of globby has a dependency tree which does pull in a fixed version of glob-parent.

    opened by isuftin 7
  • Doesn't copy

    Doesn't copy "__"-prefixed files

    cpy("path/to/__*.ext", destination)
    

    doesn't copy, and throws no errors.

    With the files renamed, this copies just fine:

    cpy("path/to/_*.ext", destination)
    
    opened by stevenvachon 7
  • [RFC] copy recursively

    [RFC] copy recursively

    At least copying recursively makes it necessary to use a two step approach:

    1. gather all files and folders to process
    2. do the actual copy

    Substantial advantages:

    • [x] determine errors due to mutually recursively linked directories in advance (see test below)
    • [ ] remove duplicated tasks (same source and destination)
    • [ ] determine copy tasks with same destination to throw errors in advance
    • [ ] calculate the total size during the first step, and emitting the progress during the second step

    The current approach of the first step:

    1. use globby to gather all files and directories
    2. for each directory path: re-glob with path + '/**/*'

    @all Comments on all aspects are highly welcome.

    opened by schnittstabil 7
  • Create destination directory if doesn't exist?

    Create destination directory if doesn't exist?

    When no destination directory is present, the attempt to copy files there results in error:

    CpyError: `src` and `dest` required
    

    Is there any way to configure to have it instead created like e.g. the default cp?

    opened by dmitriz 7
  • Adding file sourcePath and destinationPath to the progress

    Adding file sourcePath and destinationPath to the progress

    It would be great if the progress object would provide the information about the sourcePath and destinationPath.

    One of my use cases requires copying folders with many files. The information about which file is being copied would be very useful.

    I took a quick look at the code and the internal library cp-file already provides the desired information.

    Is there any reason not to add this information to the ProgressData object?

    {
      sourcePath: string,         <--
      destinationPath: string,    <--
      completedFiles: number,
      totalFiles: number,
      completedSize: number,
      percent: number,
    }
    
    enhancement help wanted 
    opened by CuddlySheep 1
  • wildcard vs explicit paths have different output

    wildcard vs explicit paths have different output

    given the following file structure:

    src/
    ├── hello-world.js
    └── README.md
    

    running the following with 9.0.1:

    cpy([
      'src/*.md', 
      'src/hello-world.js'
    ], 'dist')
    

    creates:

    dist/
    ├── src/
    │   └── hello-world.js
    └── README.md
    

    Apologies if I misunderstood, but is this expected?

    I would expect both globs to create the same out structure.

    example here: https://replit.com/join/obiaxjzgca-sndrs

    bug help wanted 
    opened by sndrs 3
  • Feature: preserveTimestamps

    Feature: preserveTimestamps

    AFAICT: cpy uses graceful-fs, which in turn should use fs.copyFile to copy files. How fs.copyFile handles timestamps seems to be platform dependent. Now there's a new fs.cp in recent NodeJs versions that has a special option called preserveTimestamps, fs-extra has it too.

    So I would like to propose to add this option in cpy as well - not only for files, but for directories too (cp -a).

    enhancement help wanted 
    opened by jeffrson 0
  • Option 'parents' missing

    Option 'parents' missing

    Hey, i am not able to copy a directory structure with the whole structure any more. With v9.x i always end up getting a flattened result - what is my error?

    In v8 i used

    await cpy('**', destination, { parents: true, cwd: source });

    and now i thought

    await cpy(source, destination); or maybe await cpy(source+'/**', destination);

    should work?

    opened by h-evers 3
  • Failed to copy files into a drive (C:, D:)  on Windows

    Failed to copy files into a drive (C:, D:) on Windows

    I tried cpy and it's awesome! However, when I try it on windows, copying a file from C: to the basedir of E:, I got an error saying it failed to create the E: directory. This is the error message:

    Cannot copy from `C:/hello.txt` to `E:\hello.txt`: Cannot create directory `E:\`: EPERM: operation not permitted, mkdir 'E:\'
    

    Hope it will be fixed soon :)

    bug help wanted 
    opened by kimlimjustin 1
Releases(v9.0.1)
  • v9.0.1(Mar 7, 2022)

  • v9.0.0(Feb 27, 2022)

    Breaking

    • This package is now pure ESM. Please read this.
    • Require Node.js 12

    Recursive by default

    • parents option was removed
    • to get flat list of files use flat: true option

    Example directory structure:

    - .github/workflows/main.yml
    - .github/funding.yml
    

    Command: cpy('.github/**', 'dest')

    Old output:

    - dest/funding.yml
    - dest/main.yml
    

    New output:

    - dest/workflows/main.yml
    - dest/main.yml
    

    Recreate old parents: true

    Example directory structure:

    - .github/workflows/main.yml
    - .github/funding.yml
    

    Old: cpy('.github/**', 'dest', {parents: true})

    New: cpy('.github', 'dest')

    Output:

    - dest/.github/workglows/main.yml
    - dest/.github/funding.yml
    

    Recreate old parents: false

    Example directory structure:

    - .github/workflows/main.yml
    - .github/funding.yml
    

    Old: cpy('.github/**', 'dest', {parents: false})

    New: cpy('.github', 'dest', {flat: true})

    Output:

    - dest/main.yml
    - dest/funding.yml
    

    Copy all package.json and preserve folder structure

    Old: cpy('node_modules/**/package.json', 'dest', {parents: true})

    Old output:

    New: cpy('node_modules/**/package.json', 'dest')

    New output:

    https://github.com/sindresorhus/cpy/compare/v8.1.2...v9.0.0

    Source code(tar.gz)
    Source code(zip)
  • v8.1.2(Mar 5, 2021)

  • v8.1.1(Sep 2, 2020)

  • v8.1.0(Mar 7, 2020)

  • v8.0.1(Feb 21, 2020)

  • v8.0.0(Dec 6, 2019)

  • v7.3.0(Jun 11, 2019)

    Enhancements:

    • Return the destination file paths of the copied files (#46) cfacfc8

    https://github.com/sindresorhus/cpy/compare/v7.2.0...v7.3.0

    Source code(tar.gz)
    Source code(zip)
  • v7.2.0(Apr 3, 2019)

  • v7.1.0(Mar 6, 2019)

  • v7.0.0(May 12, 2018)

Owner
Sindre Sorhus
Full-Time Open-Sourcerer. Wants more empathy & kindness in open source. Focuses on Swift & JavaScript. Makes macOS apps, CLI tools, npm packages. Likes unicorns
Sindre Sorhus
Move files and directories to the trash

Move files and folders to the trash Works on macOS (10.12+), Linux, and Windows (8+). Note: The Linux implementation is not very good and not maintain

Sindre Sorhus 2.4k Dec 29, 2022
HMSC (How Much Stuffs CLI) analyst for your files and folders

HMSC ?? About HMSC (How Much Stuffs CLI) analyst for your files and folders ?? Screenshot ?? Requirements Node.js NPM ?? Installation $ npm i -g hmsc

Abdullah Veliyev 26 Jan 10, 2022
Run a command when a certain file exists, and/or watch files to rerun on changes

Run a command when a certain file exists, and/or watch files to rerun on changes

EGOIST 45 Sep 23, 2022
Windows command line tool to block outbound connections for files within a directory.

fwg A Windows command line tool to block outbound connections for files within a directory. fwg utilizes the power of PowerShell and Windows Network S

raymond wang 3 Jul 19, 2022
Detect copy-pasted and structurally similar code

Detect copy-pasted and structurally similar JavaScript code. Requires Node.js 6.0+, and supports ES6, JSX as well as Flow. Note: the project has been

Daniel St. Jules 3.5k Dec 26, 2022
mutate a copy of data without changing the original source

immutability-helper Mutate a copy of data without changing the original source Setup via NPM npm install immutability-helper --save This is a drop-in

Moshe Kolodny 5.1k Dec 29, 2022
Detect copy-pasted and structurally similar code

Detect copy-pasted and structurally similar JavaScript code. Requires Node.js 6.0+, and supports ES6, JSX as well as Flow. Note: the project has been

Daniel St. Jules 3.5k Dec 26, 2022
Minecraft-classic - A working copy of the original classic.minecraft.net website.

minecraft-classic Just a copy of https://classic.minecraft.net/ (or at least as much as I could). This is a working copy of the Minecraft Classic webs

null 4 Oct 19, 2022
Emoji - Use emoji names instead of Unicode strings. Copy-pasting emoji sucks.

Grammy Emoji Adds emoji parsing for grammY. Check out the official documentation for this plugin. While this draft is working, we still do not recomme

null 8 Sep 5, 2022
NoPrint.js - Disable Print, Screenshot, Copy & Paste in HTML by JavaScript.

NoPrint.js Disable Print, Screenshot, Copy & Paste in HTML by JavaScript. NoPrint.js is a small and neat open source JS library that disables print, s

null 33 Dec 26, 2022
Lightweight library to copy PNG and JPG images to clipboard

Copy Image Clipboard Created with ❤️ by Luan Eduardo da Costa | Follow me on Linkedin ?? About This library allows you to copy JPG and PNG images (onl

Luan Eduardo da Costa 34 Nov 29, 2022
Copypaster Has your project structure gotten so complex that to add a new feature you need to copy

Copypaster Has your project structure gotten so complex that to add a new feature you need to copy, paste and rename tens or hundreds of files each ti

null 2 Nov 4, 2022
A simple copy of the Reddit app using it's API in React Native

A simple copy of the Reddit app using it's API in React Native

Arthur 10 Nov 12, 2022
A style export tool that live edits and exports code ready to copy / paste

Awesome Title Generator A style export tool that live edits and exports code ready to copy / paste. Features Edits text and live previews it CSS and R

Crhistian de Oliveira 19 Oct 7, 2022
A collection of scripts to build offline documentation for your favourite frameworks/libraries. Simply search, copy/paste the commands and enjoy.

Offline-docs A collection of scripts to build offline documentation for your favourite frameworks/libraries. Simply search, copy/paste the commands an

Naveen Namani 37 Dec 24, 2022
Browser extension to copy the page title and URL as rich text.

Copy Rich Link Browser extension to copy the page title and URL as rich text. Useful for pasting links to Slack, Google Docs, etc. Usage Install Insta

Ryo Nakamura 19 Dec 17, 2022
Copy/paste detecting GitHub Action for programming source code (jscpd)

dry-code Copy/paste detecting GitHub Action for programming source code with jscpd Action inputs Action input Description Default Value Required optio

null 5 Dec 14, 2022
🫥 Copy repository without the git information for self-managed gitlab, very fast.

English | 简体中文 degitlab ?? degitlab -> de-git-lab Copy repository without the git information for self-managed gitlab, very fast. Why? In self-managed

東澔 6 Oct 16, 2022
cheap, open-src copy of discord.id

discord-user-checker discord-user-checker is web app to check user's information Installation Clone repository. Download Git Node.js Then type in fold

Najlekk 4 Oct 26, 2022
Copy to clipboard jQuery plugin.

jQuery - Copy to clipboard Plugin jQuery Copy to clipboard plugin - copy any text to the user site's clipboard. Operates on the basis of creating hidd

Milan Kyncl 16 Aug 21, 2022