Created
February 8, 2025 15:16
-
-
Save welingtonms/7265f0dad61c8f6097209935a66dff07 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const path = require('path'); | |
// Get command line arguments | |
const [oldExt, newExt, targetDir] = process.argv.slice(2); | |
if (!oldExt || !newExt) { | |
console.error( | |
'Usage: node rename-extensions.js <old-extension> <new-extension> [directory]', | |
); | |
console.error('Example: node rename-extensions.js jsx tsx ./src'); | |
console.error( | |
'Note: If directory is not specified, current directory will be used', | |
); | |
process.exit(1); | |
} | |
// Use provided directory or fallback to current directory | |
const startDirectory = targetDir ? path.resolve(targetDir) : process.cwd(); | |
// Verify the directory exists | |
if (!fs.existsSync(startDirectory)) { | |
console.error(`Error: Directory "${startDirectory}" does not exist`); | |
process.exit(1); | |
} | |
// Function to rename files | |
function renameFiles(directory) { | |
fs.readdirSync(directory).forEach((file) => { | |
const fullPath = path.join(directory, file); | |
// Check if it's a directory | |
if (fs.statSync(fullPath).isDirectory()) { | |
renameFiles(fullPath); // Recurse into subdirectories | |
return; | |
} | |
// Check if file ends with the old extension | |
if (file.endsWith(`.${oldExt}`)) { | |
// Handle both file.ext and file.something.ext patterns | |
const newName = file.slice(0, -oldExt.length) + newExt; | |
const newPath = path.join(directory, newName); | |
fs.renameSync(fullPath, newPath); | |
// Show relative path from starting directory | |
const relativePath = path.relative(startDirectory, directory); | |
const location = relativePath ? `${relativePath}/` : ''; | |
console.log(`Renamed: ${location}${file} → ${newName}`); | |
} | |
}); | |
} | |
// Start renaming from specified directory | |
try { | |
console.log(`Starting in directory: ${startDirectory}`); | |
renameFiles(startDirectory); | |
console.log('Done!'); | |
} catch (error) { | |
console.error('Error:', error.message); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment