-
Notifications
You must be signed in to change notification settings - Fork 280
/
Copy pathpath_operations.ts
73 lines (61 loc) · 2.51 KB
/
path_operations.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
/**
* @title Path operations
* @difficulty beginner
* @tags cli
* @run -R <url>
* @resource {https://jsr.io/@std/path/doc} Doc: @std/path
* @resource {https://docs.deno.com/api/deno/~/Deno.cwd} Deno: Deno.cwd
* @group File System
*
* Many applications need to manipulate file paths in one way or another.
* The Deno Standard Library provides simple utilities for this.
*/
// First we will import the module from the Deno Standard Library
import * as path from "jsr:@std/path";
import * as posix from "jsr:@std/path/posix";
import * as windows from "jsr:@std/path/windows";
// Converting from a file url to a directory can be done simply by the `fromFileUrl`
// method from the appropriate implementation.
const p1 = posix.fromFileUrl("file:///home/foo");
const p2 = windows.fromFileUrl("file:///home/foo");
console.log(`Path 1: ${p1} Path 2: ${p2}`);
// We can also choose to not specify the platform and automatically use whatever Deno is running on
const p3 = path.fromFileUrl("file:///home/foo");
console.log(`Path on current OS: ${p3}`);
// We can get the last part of a file path using the basename method
const p = path.basename("./deno/is/awesome/mod.ts");
console.log(p); // mod.ts
// We can get the directory of a file path using the dirname method
const base = path.dirname("./deno/is/awesome/mod.ts");
console.log(base); // ./deno/is/awesome
// We can get the extension of a file path using the extname method
const ext = path.extname("./deno/is/awesome/mod.ts");
console.log(ext); // .ts
// We can format a path using a FormatInputPathObject
const formatPath = path.format({
root: "/",
dir: "/home/user/dir",
ext: ".html",
name: "index",
});
console.log(formatPath); // "/home/user/dir/index.html"
// When we want to make our code cross-platform, we can use the join method.
// This joins any number of string by the OS-specific file separator. On
// Mac OS this would be foo/bar. On windows, this would be foo\bar.
const joinPath = path.join("foo", "bar");
console.log(joinPath);
// We can get the current working directory using the built-in cwd method
const current = Deno.cwd();
console.log(current);
// We can get the directory name of the current module using the built-in
// dirname method
const dirname = import.meta.dirname;
console.log(dirname);
// We can get the URL of the current module using the built-in
// url method
const url = import.meta.url;
console.log(url);
// We can get the file name of the current module using the built-in
// filename method
const filename = import.meta.filename;
console.log(filename);