Last active
February 21, 2023 08:15
-
-
Save LordZombi/22cb2aaa223512c5a8f1a922333ec703 to your computer and use it in GitHub Desktop.
Rename files to kebab-case (AI generated)
This file contains hidden or 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'); | |
function removeAccents(str) { | |
return str.normalize('NFD').replace(/[\u0300-\u036f]/g, ''); | |
} | |
function kebabCase(str) { | |
return str | |
.replace(/[^\w\s-]/g, '') // Remove non-Latin characters and keep spaces and hyphens | |
.replace(/\s+/g, '-') // Replace spaces with hyphens | |
.replace(/_/g, '-') // Replace spaces with hyphens | |
.toLowerCase(); | |
} | |
function renameRecursive(rootDir) { | |
const files = fs.readdirSync(rootDir); | |
files.forEach((file) => { | |
const filePath = path.join(rootDir, file); | |
const isDirectory = fs.statSync(filePath).isDirectory(); | |
// Recursively rename subdirectories and files | |
if (isDirectory) { | |
renameRecursive(filePath); | |
} | |
// Rename the file or directory to kebab-case | |
const fileExt = path.extname(file); | |
const fileName = path.basename(file, fileExt); | |
const kebabCaseName = kebabCase(removeAccents(fileName)); | |
const newFilePath = path.join(rootDir, kebabCaseName + fileExt.toLowerCase()); | |
if (newFilePath !== filePath) { | |
fs.renameSync(filePath, newFilePath); | |
console.log(`Renamed ${filePath} to ${newFilePath}`); | |
} | |
}); | |
} | |
const rootDir = './public/images/'; | |
renameRecursive(rootDir); | |
console.log('Done!'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment