Using path.extname to Extract File Extensions in Node.js
📖 Scenario: You are building a simple Node.js script to help organize files by their extensions. To do this, you need to extract the file extension from each filename.
🎯 Goal: Create a Node.js script that uses path.extname to get the file extension from a list of filenames.
📋 What You'll Learn
Create an array called
files with the exact filenames: 'report.pdf', 'photo.jpg', 'archive.zip', 'notes.txt'Create a variable called
extToFind and set it to '.jpg'Use a
for loop with the variable file to iterate over files and create an array extensions that stores the extension of each file using path.extname(file)Add a final line that exports the
extensions array using module.exports = extensions💡 Why This Matters
🌍 Real World
Extracting file extensions is useful when organizing files, validating uploads, or processing files differently based on type.
💼 Career
Understanding how to use Node.js built-in modules like path and how to manipulate arrays is essential for backend JavaScript development.
Progress0 / 4 steps