All files / fs / unstable_create.ts

0.00% Branches 0/2
44.00% Lines 11/25
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
 
 
x1
x1
x1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x1
x4
x4
 
 
 
 
 
 
 
x4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x1
x4
x4
 
 
 
 
 
 
 
x4


























I




























I






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

import { isDeno } from "./_utils.ts";
import { mapError } from "./_map_error.ts";
import { open, openSync } from "./unstable_open.ts";
import type { FsFile } from "./unstable_types.ts";

/**
 * Creates a file if none exists or truncates an existing file and resolves to
 * an instance of {@linkcode FsFile}.
 *
 * Requires `allow-read` and `allow-write` permissions.
 *
 * @example Usage
 * ```ts ignore
 * import { create } from "@std/fs/unstable-create";
 * const file = await create("/foo/bar.txt");
 * ```
 *
 * @tags allow-read, allow-write
 *
 * @param path The path to the newly created file.
 * @returns A promise that resolves to a {@linkcode FsFile} instance.
 */
export async function create(path: string | URL): Promise<FsFile> {
  if (isDeno) {
    return Deno.create(path);
  } else {
    try {
      return await open(path, { create: true, write: true, truncate: true });
    } catch (error) {
      throw mapError(error);
    }
  }
}

/**
 * Creates a file if none exists or truncates an existing file and returns
 * an instance of {@linkcode FsFile}.
 *
 * Requires `allow-read` and `allow-write` permissions.
 *
 * @example Usage
 * ```ts ignore
 * import { createSync } from "@std/fs/unstable-create";
 * const file = createSync("/foo/bar.txt");
 * ```
 *
 * @tags allow-read, allow-write
 *
 * @param path The path to the newly created file.
 * @returns A {@linkcode FsFile} instance.
 */
export function createSync(path: string | URL): FsFile {
  if (isDeno) {
    return Deno.createSync(path);
  } else {
    try {
      return openSync(path, { create: true, write: true, truncate: true });
    } catch (error) {
      throw mapError(error);
    }
  }
}