0
0
DenoHow-ToBeginner ยท 3 min read

How to Use Path Module in Deno: Syntax and Examples

In Deno, you use the path module by importing it from https://deno.land/std/path/mod.ts. This module provides functions like join, basename, and dirname to work with file paths easily and safely.
๐Ÿ“

Syntax

To use the path module in Deno, import it from the official standard library URL. You can then call its functions to manipulate file paths.

  • import: brings the module into your code.
  • join(): combines path segments into one path.
  • basename(): gets the last part of a path (file or folder name).
  • dirname(): gets the folder path without the file.
typescript
import * as path from "https://deno.land/std/path/mod.ts";

const fullPath = path.join("folder", "subfolder", "file.txt");
const fileName = path.basename(fullPath);
const folderPath = path.dirname(fullPath);
๐Ÿ’ป

Example

This example shows how to join path parts, get the file name, and get the directory path using the path module in Deno.

typescript
import * as path from "https://deno.land/std/path/mod.ts";

const parts = ["users", "john", "docs", "notes.txt"];
const fullPath = path.join(...parts);
console.log("Full path:", fullPath);

const fileName = path.basename(fullPath);
console.log("File name:", fileName);

const dirName = path.dirname(fullPath);
console.log("Directory path:", dirName);
Output
Full path: users/john/docs/notes.txt File name: notes.txt Directory path: users/john/docs
โš ๏ธ

Common Pitfalls

Some common mistakes when using the path module in Deno include:

  • Not importing the module from the correct URL, which causes errors.
  • Using string concatenation instead of path.join(), which can cause wrong paths on different operating systems.
  • Confusing basename() and dirname() results.
typescript
/* Wrong way: string concatenation can break on Windows */
const wrongPath = "folder" + "/" + "file.txt";

/* Right way: use path.join for cross-platform safety */
import * as path from "https://deno.land/std/path/mod.ts";
const rightPath = path.join("folder", "file.txt");
๐Ÿ“Š

Quick Reference

FunctionDescriptionExample
join(...paths)Joins multiple path segments into one pathpath.join('a', 'b', 'c') โ†’ 'a/b/c'
basename(path)Returns the last part of the path (file or folder name)path.basename('a/b/c.txt') โ†’ 'c.txt'
dirname(path)Returns the directory part of the pathpath.dirname('a/b/c.txt') โ†’ 'a/b'
extname(path)Returns the file extensionpath.extname('a/b/c.txt') โ†’ '.txt'
isAbsolute(path)Checks if the path is absolutepath.isAbsolute('/a/b') โ†’ true
โœ…

Key Takeaways

Always import the path module from https://deno.land/std/path/mod.ts in Deno.
Use path.join() to safely combine path segments across operating systems.
Use basename() to get the file name and dirname() to get the folder path.
Avoid manual string concatenation for paths to prevent errors.
The path module helps write clean, cross-platform file path code in Deno.