Introduction
These functions help you get parts of a file path easily. basename gets the file name, and dirname gets the folder path.
Jump into concepts and practice - no test required
These functions help you get parts of a file path easily. basename gets the file name, and dirname gets the folder path.
const path = require('path');
path.basename(pathString[, ext])
path.dirname(pathString)pathString is the full path you want to work with.
ext in basename is optional and removes the file extension if given.
file.txt from the full path.const path = require('path'); const fileName = path.basename('/home/user/docs/file.txt'); console.log(fileName);
/home/user/docs from the full path.const path = require('path'); const folder = path.dirname('/home/user/docs/file.txt'); console.log(folder);
file.const path = require('path'); const fileNameNoExt = path.basename('/home/user/docs/file.txt', '.txt'); console.log(fileNameNoExt);
This program shows how to get the file name, folder path, and file name without extension from a full file path.
const path = require('path'); const fullPath = '/users/alex/projects/app/index.js'; const fileName = path.basename(fullPath); const folderName = path.dirname(fullPath); const fileNameNoExt = path.basename(fullPath, '.js'); console.log('File name:', fileName); console.log('Folder path:', folderName); console.log('File name without extension:', fileNameNoExt);
These functions work with both Windows and Unix-style paths.
Use basename with the extension argument to remove file extensions easily.
path.basename gets the file name from a full path.
path.dirname gets the folder path from a full path.
They help split paths into useful parts for file handling.
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.