Skip to content

Instantly share code, notes, and snippets.

@thebiltheory
Last active February 27, 2024 03:53
Show Gist options
  • Save thebiltheory/57d58011951c69998b20bd5bad84988d to your computer and use it in GitHub Desktop.
Save thebiltheory/57d58011951c69998b20bd5bad84988d to your computer and use it in GitHub Desktop.
Generate an array of items from the content of a folder
const fs = require("fs");
const path = require("path");
const nodeUtils = require("../utils/node.utils");
const directoryPath: string = path.join(__dirname, "../assets/icons");
fs.readdir(
directoryPath,
(err: NodeJS.ErrnoException | null, files: string[]) => {
if (err) {
console.error("Error reading directory", err);
return;
}
const options: { label: string; value: string }[] = files.map((file) => ({
label: nodeUtils.fileNameToUIName(file),
// label: file.replace(/\..+$/, ""), // Remove file extension
value: file,
}));
const configContent: string = `export const iconsOptions = ${JSON.stringify(
options,
null,
2
)};\n`;
fs.writeFile(
path.join(__dirname, "../content/icons-list.ts"),
configContent,
{
flag: "w",
},
(err: any) => {
if (err) {
console.error("Error writing file", err);
} else {
console.log("File written successfully");
}
}
);
}
);
/**
* Transforms a file name into a UI-friendly name.
* - Replaces underscores and dashes with spaces.
* - Capitalizes the first letter of each word.
* @param fileName The file name to transform.
* @return The UI-friendly name.
*/
function fileNameToLabel(fileName: string): string {
// Remove the file extension
let nameWithoutExtension: string = fileName.replace(/\..+$/, "");
// Replace underscores and dashes with spaces
let nameWithSpaces: string = nameWithoutExtension.replace(/[_-]/g, " ");
// Capitalize the first letter of each word
let uiFriendlyName: string = nameWithSpaces.replace(/\b\w/g, (char: string) =>
char.toUpperCase()
);
return uiFriendlyName;
}
module.exports = { fileNameToLabel }
{
// ... shortened for brievety
scripts: {
"generate:icons": "ts-node scripts/generate-icon-list.ts",
}
// ... shortened for brievety
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment