The path Module
6 min read
The path Module
The path module provides utilities for working with file and directory paths. It normalises separators automatically, so code written on macOS (using /) works correctly on Windows (using \) without changes.
js
const path = require("path");
// Join segments into a single path
const full = path.join("/home", "user", "projects", "app.js");
console.log(full); // /home/user/projects/app.js
// Resolve to an absolute path
const abs = path.resolve("src", "index.js");
console.log(abs); // /current/working/dir/src/index.js
// Get the directory name
console.log(path.dirname("/home/user/app.js")); // /home/user
// Get the file name
console.log(path.basename("/home/user/app.js")); // app.js
console.log(path.basename("/home/user/app.js", ".js")); // app
// Get the extension
console.log(path.extname("/home/user/app.js")); // .js
// Parse into an object
console.log(path.parse("/home/user/app.js"));
// { root: '/', dir: '/home/user', base: 'app.js', ext: '.js', name: 'app' }Use path.join for concatenating path segments. Use path.resolve when you need an absolute path relative to the current working directory.
Ready to test yourself?
Practice Node.js— quiz & coding exercises