Node.js: Code Outside the Browser / Built in Modules

Path Module

πŸ“¦ The path Module

path is a built-in Node.js module for working with file and folder paths β€” joining them, pulling them apart, and making sure they work correctly across Windows, Mac, and Linux (which use different slashes).

const path = require('path');

πŸ”— Joining Paths

const fullPath = path.join('myFolder', 'sub', 'info.txt');
console.log(fullPath);

Output:

myFolder/sub/info.txt
  • path.join(...) glues path segments together into one clean path.

  • It automatically uses the right slash for the OS (/ on Mac/Linux, \ on Windows) β€” no manual string concatenation needed.

  • It also cleans up extra slashes, so path.join('a/', '/b') still gives you a/b, not a//b.

project/
└── myFolder/
    └── sub/
        └── info.txt      ← the path this points to

πŸ“ Resolving Absolute Paths

const absolute = path.resolve('myFolder', 'info.txt');
console.log(absolute);

Output (if run from /Users/bhaskar/project):

/Users/bhaskar/project/myFolder/info.txt
  • path.resolve(...) builds a full, absolute path, starting from your current working directory.

  • Unlike join, which just glues segments together as-is, resolve figures out where that path actually lives on disk.

  • Useful when a script needs to know the real location of a file, no matter where it's run from.


🏷️ Getting Parts of a Path

const filePath = '/project/myFolder/info.txt';

console.log(path.basename(filePath)); // 'info.txt'
console.log(path.dirname(filePath));  // '/project/myFolder'
console.log(path.extname(filePath));  // '.txt'
  • basename(path) returns just the file name at the end of the path.

  • dirname(path) returns everything except the file name β€” the folder it lives in.

  • extname(path) returns the file extension, including the dot.

/project/myFolder/info.txt
              β””β”€β”€β”¬β”€β”€β”˜β””β”€β”¬β”€β”˜
            dirname  basename
                        β””β”¬β”˜
                      extname

🧩 Breaking a Path Fully Apart

const parsed = path.parse('/project/myFolder/info.txt');
console.log(parsed);

Output:

{
  root: '/',
  dir: '/project/myFolder',
  base: 'info.txt',
  ext: '.txt',
  name: 'info'
}
  • path.parse(path) splits a path into all its pieces at once β€” root, directory, full file name, extension, and name without the extension.

  • Handy when you need more than one part of the path and don't want to call basename, dirname, and extname separately.


πŸ” Reversing It: Building a Path from Parts

const built = path.format({
  dir: '/project/myFolder',
  base: 'info.txt'
});
console.log(built); // '/project/myFolder/info.txt'
  • path.format(obj) does the opposite of path.parse β€” turns an object of path pieces back into a path string.


βœ… Checking & Cleaning Paths

console.log(path.isAbsolute('/project/info.txt')); // true
console.log(path.isAbsolute('info.txt'));           // false

console.log(path.normalize('myFolder//sub/../info.txt')); // 'myFolder/info.txt'
  • isAbsolute(path) tells you whether a path starts from the root (true) or is relative to somewhere else (false).

  • normalize(path) cleans up messy paths β€” collapsing double slashes and resolving .. and . segments β€” without needing the file to actually exist.


πŸ’‘ Why Use path Instead of Plain Strings?

  • Writing 'myFolder' + '/' + 'info.txt' breaks on Windows, where paths use \ instead of /.

  • path methods handle that difference automatically, so the same code works on every OS.

  • Combine it with fs to build reliable, cross-platform file operations:

const fs = require('fs');
const path = require('path');

const filePath = path.join(__dirname, 'myFolder', 'info.txt');
fs.writeFileSync(filePath, 'Hello!');
  • __dirname is a built-in variable holding the folder your current script lives in β€” combining it with path.join guarantees the file goes in the right place, regardless of where the script is run from.