deno.land / std@0.224.0 / path / posix / dirname.ts

dirname.ts
View Documentation
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
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.// This module is browser compatible.
import { assertArg } from "../_common/dirname.ts";import { stripTrailingSeparators } from "../_common/strip_trailing_separators.ts";import { isPosixPathSeparator } from "./_util.ts";
/** * Return the directory path of a `path`. * * @example * ```ts * import { dirname } from "https://deno.land/std@$STD_VERSION/path/dirname.ts"; * * console.log(dirname("/home/user/Documents/")); // "/home/user" * console.log(dirname("/home/user/Documents/image.png")); // "/home/user/Documents" * ``` * * @param path - path to extract the directory from. */export function dirname(path: string): string { assertArg(path);
let end = -1; let matchedNonSeparator = false;
for (let i = path.length - 1; i >= 1; --i) { if (isPosixPathSeparator(path.charCodeAt(i))) { if (matchedNonSeparator) { end = i; break; } } else { matchedNonSeparator = true; } }
// No matches. Fallback based on provided path: // // - leading slashes paths // "/foo" => "/" // "///foo" => "/" // - no slash path // "foo" => "." if (end === -1) { return isPosixPathSeparator(path.charCodeAt(0)) ? "/" : "."; }
return stripTrailingSeparators( path.slice(0, end), isPosixPathSeparator, );}
std

Version Info

Tagged at
6 months ago