0
0
Node.jsframework~15 mins

path.basename and path.dirname in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Using path.basename and path.dirname in Node.js
📖 Scenario: You are working on a Node.js script that processes file paths. You want to extract the file name and the directory name from a given file path.
🎯 Goal: Build a simple Node.js script that uses path.basename to get the file name and path.dirname to get the directory name from a file path string.
📋 What You'll Learn
Import the built-in path module
Create a variable with a specific file path string
Use path.basename to get the file name
Use path.dirname to get the directory name
💡 Why This Matters
🌍 Real World
File path manipulation is common in scripts that organize, move, or analyze files on your computer or server.
💼 Career
Understanding how to extract parts of file paths is useful for backend developers, DevOps engineers, and anyone working with file systems in Node.js.
Progress0 / 4 steps
1
Import the path module and create a file path variable
Write code to import the built-in path module using require('path'). Then create a variable called filePath and set it to the string "/home/user/docs/letter.txt".
Node.js
Need a hint?

Use const path = require('path') to import the module. Then assign the exact string "/home/user/docs/letter.txt" to filePath.

2
Create variables for base name and directory name
Create two variables: baseName and dirName. Set baseName to the result of path.basename(filePath). Set dirName to the result of path.dirname(filePath).
Node.js
Need a hint?

Use path.basename(filePath) to get the file name and path.dirname(filePath) to get the directory path.

3
Add a variable for file extension
Create a variable called extName and set it to the result of path.extname(filePath) to get the file extension.
Node.js
Need a hint?

Use path.extname(filePath) to get the file extension like '.txt'.

4
Export the variables as a module
Add a module.exports statement to export an object with baseName, dirName, and extName properties.
Node.js
Need a hint?

Use module.exports = { baseName, dirName, extName } to export the variables.