-
Notifications
You must be signed in to change notification settings - Fork 574
/
exists.ts
83 lines (81 loc) · 2.34 KB
/
exists.ts
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
74
75
76
77
78
79
80
81
82
83
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
/**
* Test whether or not the given path exists by checking with the file system.
*
* Note: do not use this function if performing a check before another operation on that file. Doing so creates a race condition. Instead, perform the actual file operation directly.
*
* Bad:
* ```ts
* import { exists } from "https://deno.land/std@$STD_VERSION/fs/mod.ts";
*
* if (await exists("./foo.txt")) {
* await Deno.remove("./foo.txt");
* }
* ```
*
* Good:
* ```ts
* // Notice no use of exists
* try {
* await Deno.remove("./foo.txt");
* } catch (error) {
* if (!(error instanceof Deno.errors.NotFound)) {
* throw error;
* }
* // Do nothing...
* }
* ```
* @see https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use
* @deprecated (will be removed after 0.157.0) Checking the state of a file before using it causes a race condition. Perform the actual operation directly instead.
*/
export async function exists(filePath: string | URL): Promise<boolean> {
try {
await Deno.lstat(filePath);
return true;
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
return false;
}
throw error;
}
}
/**
* Test whether or not the given path exists by checking with the file system.
*
* Note: do not use this function if performing a check before another operation on that file. Doing so creates a race condition. Instead, perform the actual file operation directly.
*
* Bad:
* ```ts
* import { existsSync } from "https://deno.land/std@$STD_VERSION/fs/mod.ts";
*
* if (existsSync("./foo.txt")) {
* Deno.removeSync("./foo.txt");
* }
* ```
*
* Good:
* ```ts
* // Notice no use of existsSync
* try {
* Deno.removeSync("./foo.txt");
* } catch (error) {
* if (!(error instanceof Deno.errors.NotFound)) {
* throw error;
* }
* // Do nothing...
* }
* ```
* @see https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use
* @deprecated (will be removed after 0.157.0) Checking the state of a file before using it causes a race condition. Perform the actual operation directly instead.
*/
export function existsSync(filePath: string | URL): boolean {
try {
Deno.lstatSync(filePath);
return true;
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
return false;
}
throw error;
}
}