path.dirname and basename
- Node.js course
- Beginner
- Lesson 109/116
- 5 min
Learn path.dirname and path.basename.
dirname and basename
path.dirname returns the directory part of a path, while path.basename returns the file name. If you pass the extension as a second argument to basename, it strips it.
path.dirname('/a/b/c.txt'); // '/a/b'
path.basename('/a/b/c.txt'); // 'c.txt'
path.basename('/a/b/c.txt', '.txt'); // 'c'These methods are handy when you want only the directory or only the file name from a path. They return fewer fields than path.parse; if you need a single component, dirname or basename is shorter.
Practice Your turn: dirname and basename
Start with import path from 'path'. Write const dir = path.dirname('/a/b/c.txt') and const file = path.basename('/a/b/c.txt'). Log with console.log(dir, file).
Starter code
// Import the path module
// Get dir with dirname, name with basename, log with console.logSample solution
import path from 'path';
const dir = path.dirname('/a/b/c.txt');
const file = path.basename('/a/b/c.txt');
console.log(dir, file);Expected output
/a/b c.txt
dirname vs basename
dirname drops the last segment of a path and returns the directory part. basename does the opposite: it returns the last segment (the file name). Used together, they split a path into directory and file name.
const dir = path.dirname('/a/b/c.txt'); // '/a/b'
const file = path.basename('/a/b/c.txt'); // 'c.txt'Here dir gives the directory holding the file, and file gives the file name. This split is useful when moving a file to another directory or showing only its name.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: basename
import path from 'path';
const name = path.____('/a/b/c.txt');
console.log(name);
import path from 'path';
const name = path.basename('/a/b/c.txt');
console.log(name);
Explanation: basename returns the file name.
2 What does path.dirname('/a/b/c.txt') return?
- 'c.txt'
- '/a/b' Correct answer
- 'c'
- '/a/b/c.txt'
Explanation: dirname returns the directory part.
3 dirname vs basename
| Term | Meaning |
|---|---|
dirname |
directory part |
basename |
file name |
second argument |
drops extension |