Skip to content

Instantly share code, notes, and snippets.

@LordZombi
Last active February 21, 2023 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LordZombi/22cb2aaa223512c5a8f1a922333ec703 to your computer and use it in GitHub Desktop.
Save LordZombi/22cb2aaa223512c5a8f1a922333ec703 to your computer and use it in GitHub Desktop.
Rename files to kebab-case (AI generated)
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