puter.fs.copy()

Websites Puter Apps Node.js Workers

Copies a file or directory from one location to another.

Syntax

puter.fs.copy(source, destination)
puter.fs.copy(source, destination, options)
puter.fs.copy(options)

Parameters

source (String) (Required)

The path or UID of the file or directory to copy.

destination (String) (Required)

The path or UID of the destination directory. If destination is a directory then the file or directory will be copied into that directory using the same name as the source file or directory. If the destination is a file, we overwrite if overwrite is true, otherwise we error.

Relative paths resolve against the app's root directory. A relative name that looks like a UID is read as one; prefix it with ./ to address a file by that name.

options (Object) (Optional)

The options for the copy operation. The following options are supported:

Option Type Description
source String Path to the file or directory to copy. Required when passing options as the only argument.
destination String Path to the destination. Required when passing options as the only argument.
overwrite Boolean Whether to overwrite the destination file or directory if it already exists. Defaults to false.
newName String The new name to use for the copied file or directory. Defaults to undefined.
dedupeName Boolean Whether to deduplicate the file or directory name if it already exists. Defaults to false.

Return value

A Promise that will resolve to the FSItem object of the copied file or directory.

Errors

If the source file or directory does not exist, the promise will be rejected with an error.

If the destination already holds an item other than the source whose name differs from the new name only by accents or emoji, such as 😀.txt for 😁.txt, that item is never replaced. With overwrite: true the promise rejects with a conflict error, and otherwise with item_with_same_name_exists. To copy the item under a new name instead, set dedupeName: true.

Examples

Copy a file

<html>
<body>
    <script src="https://js.puter.com/v2/"></script>
    <script>
    (async () => {
        // (1) Create a random text file
        let filename = puter.randName() + '.txt';
        await puter.fs.write(filename, 'Hello, world!');
        puter.print(`Created file: "${filename}"<br>`);

        // (2) create a random directory
        let dirname = puter.randName();
        await puter.fs.mkdir(dirname);
        puter.print(`Created directory: "${dirname}"<br>`);

        // (3) Copy the file into the directory
        puter.fs.copy(filename, dirname).then((file)=>{
            puter.print(`Copied file: "${filename}" to directory "${dirname}"<br>`);
        }).catch((error)=>{
            puter.print(`Error copying file: "${error}"<br>`);
        });
    })()
    </script>
</body>
</html>