Created
February 16, 2023 22:47
-
-
Save jakebellacera/e32c9beff1c8a4748dde9df05d5c1295 to your computer and use it in GitHub Desktop.
Converts folders of SVGs into a CSV of paths to be used in an icon library.
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
import fs from "node:fs/promises"; | |
const camelize = (s) => s.replace(/-./g, (x) => x[1].toUpperCase()); | |
const getPathsFromSvg = async (path) => { | |
const svg = await fs.readFile(path, { encoding: "utf-8" }); | |
const paths = svg.match(/d="(.*?)"/); | |
if (!paths) { | |
throw new Error(`No paths in file ${path}`); | |
} | |
return paths.slice(1); | |
}; | |
const makeCsvCell = (value) => { | |
if (/,/.test(value)) { | |
return `"${value}"`; | |
} | |
if (!value || value.trim() === "") { | |
return ""; | |
} | |
return value; | |
}; | |
const writeCsvRow = async (path, columns, options = { mode: "append" }) => { | |
const row = ["name", "category", "path"] | |
.map((column) => makeCsvCell(columns[column])) | |
.join(","); | |
const data = `${row}\n`; | |
if (options.mode === "append") { | |
return fs.appendFile(path, data); | |
} | |
return fs.writeFile(path, data); | |
}; | |
const convertSvgPathsToCsv = async (foldersPath, output) => { | |
const folders = await fs.readdir(foldersPath, { withFileTypes: true }); | |
if (!folders.length) { | |
throw new Error(`no folders found in ${foldersPath}`); | |
} | |
const headerRow = { | |
name: "name", | |
category: "category", | |
path: "path", | |
}; | |
await writeCsvRow(output, headerRow, { mode: "write" }); | |
await folders.reduce(async (p, folder) => { | |
await p; | |
if (!folder.isDirectory()) { | |
return; | |
} | |
const files = await fs.readdir(`./${folder.name}`); | |
await files.reduce(async (pFile, file) => { | |
if (!/\.svg$/.test(file)) { | |
return; | |
} | |
try { | |
const paths = await getPathsFromSvg(`./${folder.name}/${file}`); | |
const row = { | |
name: camelize(file.split(".")[0]), | |
category: folder.name, | |
path: paths[0], | |
}; | |
await writeCsvRow(output, row); | |
} catch (err) { | |
console.error(err); | |
} | |
}, Promise.resolve()); | |
}, Promise.resolve()); | |
}; | |
export { convertSvgPathsToCsv }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment