0
0
Node.jsframework~10 mins

path.basename and path.dirname in Node.js - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to get the base file name from the path.

Node.js
const path = require('path');
const filePath = '/home/user/docs/file.txt';
const baseName = path.[1](filePath);
console.log(baseName);
Drag options to blanks, or click blank then click option'
Ajoin
Bbasename
Cextname
Ddirname
Attempts:
3 left
💡 Hint
Common Mistakes
Using path.dirname instead of path.basename returns the folder path, not the file name.
Using path.extname returns only the file extension.
2fill in blank
medium

Complete the code to get the directory name from the path.

Node.js
const path = require('path');
const filePath = '/home/user/docs/file.txt';
const dirName = path.[1](filePath);
console.log(dirName);
Drag options to blanks, or click blank then click option'
Abasename
Bextname
Cresolve
Ddirname
Attempts:
3 left
💡 Hint
Common Mistakes
Using path.basename returns the file name, not the directory.
Using path.extname returns the file extension.
3fill in blank
hard

Fix the error in the code to correctly get the base name of the file.

Node.js
const path = require('path');
const filePath = '/var/log/system.log';
const base = path.[1](filePath, '.log');
console.log(base);
Drag options to blanks, or click blank then click option'
Abasename
Bjoin
Cextname
Ddirname
Attempts:
3 left
💡 Hint
Common Mistakes
Using path.dirname returns the directory, not the file name.
Using path.extname returns only the extension, not the file name.
4fill in blank
hard

Fill both blanks to create a dictionary with file names as keys and their directories as values.

Node.js
const path = require('path');
const files = ['/a/b/c.txt', '/d/e/f.js', '/g/h/i.md'];
const fileDirs = {};
for (const file of files) {
  fileDirs[path.[1](file)] = path.[2](file);
}
console.log(fileDirs);
Drag options to blanks, or click blank then click option'
Abasename
Bdirname
Cextname
Djoin
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping basename and dirname causes keys and values to be reversed.
Using extname returns only file extensions, not names or directories.
5fill in blank
hard

Fill the blanks to create an object mapping file extensions to their base names.

Node.js
const path = require('path');
const files = ['/x/y/z.py', '/a/b/c.js', '/m/n/o.py'];
const extMap = {};
for (const file of files) {
  const ext = path.[1](file);
  const base = path.[2](file, ext);
  if (!extMap[ext]) {
    extMap[ext] = [];
  }
  extMap[ext].push(base);
}
console.log(extMap);
Drag options to blanks, or click blank then click option'
Aextname
Bbasename
Cext
Ddirname
Attempts:
3 left
💡 Hint
Common Mistakes
Using dirname instead of extname returns folder paths, not extensions.
Not passing the extension to basename causes the extension to remain in the base name.