All files / fs / unstable_copy_file.ts

33.33% Branches 1/3
50.00% Lines 14/28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
 
 
x1
x1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x1
x1
x1
 
x4
x4
 
 
 
 
 
 
 
x4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x1
x1
x1
 
x4
x4
 
 
 
 
 
 
 
x4





























I


































I






// Copyright 2018-2025 the Deno authors. MIT license.

import { mapError } from "./_map_error.ts";
import { getNodeFs, isDeno } from "./_utils.ts";

/**
 * Copies the contents and permissions of one file to another specified path, by default creating a
 * new file if needed, else overwriting. Fails if target path is a directory or is unwritable.
 *
 * Requires `allow-read` and `allow-write` permission.
 *
 * For a full description, see {@linkcode copyFile}.
 *
 * @example Usage
 * ```ts ignore
 * import { copyFile } from "@std/fs/unstable-copy-file";
 * copyFile("README.md", "README-Copy.md");
 * ```
 *
 * @tags allow-read, allow-write
 *
 * @param from The path of source filename to copy.
 * @param to The path of destination filename.
 */
export async function copyFile(
  from: string | URL,
  to: string | URL,
): Promise<void> {
  if (isDeno) {
    await Deno.copyFile(from, to);
  } else {
    try {
      await getNodeFs().promises.copyFile(from, to);
    } catch (error) {
      throw mapError(error);
    }
  }
}

/**
 * Synchronously copies the contents and permissions of one file to another specified path,
 * by default creating a new file if needed, else overwriting. Fails if target path is a directory
 * or is unwritable.
 *
 * Requires `allow-read` and `allow-write` permission.
 *
 * For a full description, see {@linkcode copyFileSync}.
 *
 * @example Usage
 * ```ts ignore
 * import { copyFileSync } from "@std/fs/unstable-copy-file";
 * copyFileSync("README.md", "README-Copy.md");
 * ```
 *
 * @tags allow-read, allow-write
 *
 * @param from The path of source filename to copy.
 * @param to The path of destination filename.
 */
export function copyFileSync(
  from: string | URL,
  to: string | URL,
) {
  if (isDeno) {
    Deno.copyFileSync(from, to);
  } else {
    try {
      getNodeFs().copyFileSync(from, to);
    } catch (error) {
      throw mapError(error);
    }
  }
}