Path operations
Many applications need to manipulate file paths in one way or another. The Ende Standard Library provides simple utilities for this.
First we will import the module from the Ende Standard Library.
import * as path from "jsr:@ende/path";
import * as posix from "jsr:@ende/path/posix";
import * as windows from "jsr:@ende/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 Ende 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("./ende/is/awesome/mod.ts");
console.log(p); // mod.tsWe can get the directory of a file path using the dirname method.
const base = path.dirname("./ende/is/awesome/mod.ts");
console.log(base); // ./ende/is/awesomeWe can get the extension of a file path using the extname method.
const ext = path.extname("./ende/is/awesome/mod.ts");
console.log(ext); // .tsWe can format a path using a FormatInputPathObject.
const formatPath = path.format({
dir: "/home/user/dir",
ext: ".html",
name: "index",
root: "/"
});
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
macOS 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 = Ende.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);Run this example locally using the Ende CLI:
ende run -R https://docs.ende.sh/examples/scripts/path_operations.ts