0
0
Node.jsframework~20 mins

path.basename and path.dirname in Node.js - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Path Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of path.basename with extension
What is the output of the following Node.js code using path.basename?
Node.js
import path from 'path';
const filePath = '/home/user/docs/letter.txt';
console.log(path.basename(filePath, '.txt'));
A'letter'
B'/home/user/docs/letter.txt'
C'docs'
D'letter.txt'
Attempts:
2 left
💡 Hint
The second argument to path.basename removes the file extension if it matches.
Predict Output
intermediate
2:00remaining
Output of path.dirname with nested path
What does the following code print using path.dirname?
Node.js
import path from 'path';
const filePath = '/var/www/html/index.html';
console.log(path.dirname(filePath));
A'/var/www/html/index.html'
B'html'
C'/var/www'
D'/var/www/html'
Attempts:
2 left
💡 Hint

path.dirname returns the directory part of the path, excluding the file name.

component_behavior
advanced
2:00remaining
Behavior of path.basename with trailing slash
What is the output of this code snippet using path.basename on a path with a trailing slash?
Node.js
import path from 'path';
const dirPath = '/usr/local/bin/';
console.log(path.basename(dirPath));
A'bin'
B'local'
C'' (empty string)
D'/'
Attempts:
2 left
💡 Hint
path.basename returns an empty string when the path ends with a trailing slash.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in path usage
Which option contains a syntax error when importing and using path.dirname in Node.js ES modules?
Aimport path from 'path'; console.log(path.dirname('/a/b/c.txt'));
Bconst path = require('path'); console.log(path.dirname('/a/b/c.txt'));
Cimport path from 'path'; console.log(path.dirname('/a/b/c.txt')
Dimport { dirname } from 'path'; console.log(dirname('/a/b/c.txt'));
Attempts:
2 left
💡 Hint
Check for missing parentheses or syntax mistakes in the code.
🔧 Debug
expert
2:00remaining
Why does path.basename return an empty string?
Given the code below, why does path.basename return an empty string?
Node.js
import path from 'path';
const p = '/folder/subfolder/';
console.log(path.basename(p));
ABecause the path is invalid and basename throws an error.
BBecause the path ends with a slash, so basename returns empty string.
CBecause basename always returns empty string for directories.
DBecause the path is relative, basename returns empty string.
Attempts:
2 left
💡 Hint
Think about how trailing slashes affect basename output.