title | type |
---|---|
Copy a file or directory |
file-upload |
Unlike files.mv
, which removes items from their source path when moving them to their destination path, the files.cp
method allows you to a copy a file or directory to a new location while also leaving it intact at its source.
The method looks like this:
await ipfs.files.cp(from, to, [options])
However, you now have two formatting options for from
. You can pass in either:
- an existing MFS path to a file or a directory in your own node (e.g.
/my-dir/my-file.txt
) - an IPFS path to a file or directory hosted either by you or by a peer (e.g.
/ipfs/QmWGeRAEgtsHW3ec7U4qW2CyVy7eA2mFRVbk1nb24jFyks
)
Notice that an IPFS path starts with /ipfs/
and ends with a CID.
As you saw with files.mv
, to
is the destination path in MFS, and there's an option { parents: true }
that can be used to create parent directories that don't already exist.
You can use files.cp
to perform a number of different operations:
// copy a single file into a directory
await ipfs.files.cp('/source-file.txt', '/destination-directory')
await ipfs.files.cp('/ipfs/QmWGeRAEgtsHW3ec7U4qW2CyVy7eA2mFRVbk1nb24jFyks', '/destination-directory')
// copy multiple files into a directory (note `from` is now an array)
await ipfs.files.cp(['/source-file-1.txt', '/source-file-2.txt'], '/destination-directory')
await ipfs.files.cp(['/ipfs/QmWGeRAEgtsHW3ec7U4qW2CyVy7eA2mFRVbk1nb24jFyks',
'/ipfs/QmWGeRAEgtsHW3jk7U4qW2CyVy7eA2mFRVbk1nb24jFyre'], '/destination-directory')
// copy a directory into another directory
await ipfs.files.cp('/source-directory', '/destination-directory')
await ipfs.files.cp('/ipfs/QmWGeRAEgtsHW3ec7U4qW2CyVy7eA2mFRVbk1nb24jFyks', '/destination-directory')
Gotcha! If you copy a file from an IPFS path without explicitly assigning it a filename, IPFS will set its name
property equal to its CID
. To specify a more friendly filename, you'll need to append it to the destination path like so:
await ipfs.files.cp('/ipfs/QmWGeRAEgtsHW3ec7U4qW2CyVy7eA2mFRVbk1nb24jFyks', '/destination-directory/fab-file.txt')