Last active
May 7, 2024 15:32
-
-
Save jezmck/5f3c41f34b191427213d86a35deb4a6e to your computer and use it in GitHub Desktop.
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
// samayo/country-json/country-by-flag.json | |
// node | |
const fs = require('fs'); | |
const {optimize} = require('svgo'); | |
// const filename = '2-countries-by-flag.json'; | |
const filename = 'country-by-flag.json'; | |
console.log(`Start processing SVGs within the file ${filename}`); | |
let optimizedSVGs = []; | |
fs.readFile(filename, 'utf8', (err, data) => { | |
if (err) { | |
console.error(`Error reading file: ${err}`); | |
return; | |
} | |
const json = JSON.parse(data); | |
console.log(`Processing ${json.length} countries`); | |
json.forEach((jsonElement) => { | |
let {country, flag_base64} = jsonElement; | |
if (!flag_base64) { | |
console.warn(`No flag for ${country}!`); | |
return; | |
} | |
let svgString = Buffer.from( | |
flag_base64.replace(/^data:image\/svg\+xml;base64,/, ''), | |
'base64' | |
).toString('utf8'); | |
const filename = `flags/${country}.svg`; | |
const result = optimize(svgString, { | |
path: filename, | |
multipass: true, // all other config fields are available here | |
}); | |
const buffer = Buffer.from(result.data, 'utf8'); | |
fs.writeFile(filename, buffer, (err) => { | |
if (err) { | |
console.error(`Error writing file: ${err}`); | |
return; | |
} | |
// console.log(`File written: ${filename}`); | |
}); | |
console.log(`Optimized flag for ${country}.`); | |
optimizedSVGs.push({ | |
...jsonElement, | |
flag_base64: `data:image/svg+xml;base64,${Buffer.from(result.data, 'utf8').toString('base64')}`, | |
}); | |
}); | |
const newFilename = filename.replace('.json', '') + '-optimized.json'; | |
fs.writeFile(newFilename, JSON.stringify(optimizedSVGs, null, ''), (err) => { | |
if (err) { | |
console.error(`Error creating file: ${err}`); | |
return; | |
} | |
console.log(`File created: ${newFilename}`); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment