Beginner Fundamentals

The path Module

The path module helps you build and inspect file paths in a way that works on every operating system. Windows uses backslashes while macOS and Linux use forward slashes, and path handles the difference for you.

Joining paths

path.join combines segments with the correct separator:

const path = require("path");

const full = path.join("users", "fausto", "notes.txt");
console.log(full); // users/fausto/notes.txt (on Unix)

Getting the file name

path.basename returns the last part of a path:

const path = require("path");

console.log(path.basename("/users/fausto/notes.txt")); // notes.txt

Getting the extension

path.extname returns the file extension:

const path = require("path");

console.log(path.extname("notes.txt")); // .txt
console.log(path.extname("image.png"));  // .png

Other useful methods

  • path.dirname(p) returns the folder part.
  • path.resolve(p) returns an absolute path.

Summary

Always use the path module instead of building paths by hand with strings. It keeps your code portable across systems.