Node.js Path Module
The path module helps you work with file and directory paths in a cross-platform way. It handles the differences between Windows paths (\) and Unix paths (/) automatically.
Importing
import path from 'node:path';
// or CommonJS: const path = require('path');
path.join(…paths)
Joins path segments together safely. This is the most commonly used path method.
console.log(path.join(__dirname, 'views', 'index.html'));
// /home/user/project/views/index.html
console.log(path.join('/public', 'image', 'cat.png'));
// /public/image/cat.png
Use path.join() when building file paths in your code. It ensures the correct separator is used on every platform.
path.resolve(…paths)
Resolves a sequence of paths into an absolute path. Unlike path.join(), it processes from right to left and stops once it has an absolute path.
console.log(path.resolve('views', 'index.html'));
// /home/user/current-working-directory/views/index.html
path.basename(path)
Returns the last part of a path (the filename).
console.log(path.basename('public/image/cat.png')); // cat.png
console.log(path.basename('public/image/cat.png', '.png')); // cat (strips extension)
console.log(path.basename(__filename)); // current filename, e.g. server.js
path.dirname(path)
Returns the directory portion of a path.
console.log(path.dirname(__filename));
// /home/user/dir
console.log(path.dirname('/public/image/logo.png'));
// /public/image
path.extname(path)
Returns the file extension, including the dot.
console.log(path.extname(__filename)); // .js
console.log(path.extname('cat.html')); // .html
console.log(path.extname('cat.md')); // .md
console.log(path.extname('cat')); // (empty string)
console.log(path.extname('.cat')); // (empty string)
path.parse(path)
Converts a path string into an object with root, dir, base, ext, and name properties.
console.log(path.parse('/home/user/dir/path.js'));
/*
{
root: '/',
dir: '/home/user/dir',
base: 'path.js',
ext: '.js',
name: 'path'
}
*/
path.isAbsolute(path)
Returns true if the path is absolute.
console.log(path.isAbsolute('/foo/bar')); // true
console.log(path.isAbsolute('/baz/..')); // true
console.log(path.isAbsolute('hello/')); // false
console.log(path.isAbsolute('.')); // false
path.sep
The platform-specific path separator (/ on Unix, \ on Windows).
console.log('foo/bar/baz'.split(path.sep)); // [ 'foo', 'bar', 'baz' ]
path.format(object)
Converts a path object back to a string. The inverse of path.parse(). Rarely needed in everyday code.
console.log(path.format({ dir: '/home/user/dir', base: 'path.js' }));
// /home/user/dir/path.js
What to read next
- File System
: use
path.join()to build file paths forfsoperations - Core Modules : overview of all built-in modules