Performance: path.basename and path.dirname
These functions affect CPU usage during file path processing but have negligible impact on page load or rendering speed.
Jump into concepts and practice - no test required
const path = require('path');
const fileName = path.basename(fullPath);
const dirName = path.dirname(fullPath);const fileName = fullPath.split('/').pop(); const dirName = fullPath.split('/').slice(0, -1).join('/');
| Pattern | CPU Usage | String Operations | Error Risk | Verdict |
|---|---|---|---|---|
| Manual string split/join | High | Many | Higher | [X] Bad |
| path.basename and path.dirname | Low | Minimal | Low | [OK] Good |
path.basename return when given a full file path?path.basename purposepath.dirname which returns the folder path, path.basename returns the file name part.path module?path moduledirname, all lowercase.path.dirname(pathString), so path.dirname('/home/user/file.txt') matches exactly.const path = require('path');
const fullPath = '/var/www/html/index.html';
console.log(path.basename(fullPath));
console.log(path.dirname(fullPath));path.basename(fullPath)index.html.path.dirname(fullPath)/var/www/html.const path = require('path');
const filePath = '/usr/local/bin/node';
console.log(path.baseName(filePath));
console.log(path.dirname(filePath));path.baseName is incorrect because the correct method is all lowercase basename.path module is imported correctly and dirname usage is correct, so no other errors./home/user/docs/letter.txt, how can you use path.basename and path.dirname together to print:Folder: /home/user/docsFile: letter.txtpath.dirname to get folder pathpath.dirname(filePath) returns the folder path /home/user/docs.path.basename to get file namepath.basename(filePath) returns the file name letter.txt.