Last active
November 22, 2020 21:42
-
-
Save jniac/53fee492532c2bcd904857f093ded4cb to your computer and use it in GitHub Desktop.
download google fonts (with node)
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 fetch from 'node-fetch' | |
import fs from 'fs-extra' | |
const safeName = str => str.replace(/\W/g, '-') | |
const parseFontFace = fontFace => { | |
const [, url] = fontFace.match(/url\((.*?)\)/) | |
const [, family] = fontFace.match(/font-family: '(.*?)';/) | |
const [, style] = fontFace.match(/font-style: (.*?);/) | |
const [, weight] = fontFace.match(/font-weight: (.*?);/) | |
const ext = url.match(/\.\w+$/) | |
const filename = `${safeName(family)}-${weight}-${style}${ext}` | |
fontFace = fontFace.replace(url, filename) | |
return { fontFace, family, url, filename, url } | |
} | |
const loadFont = async url => { | |
const response = await fetch(url) | |
const style = await response.text() | |
const fonts = style.match(/@font-face {[\s\S]*?}/g).map(parseFontFace) | |
const folder = safeName(fonts[0].family) | |
await fs.remove(`fonts/${folder}`) | |
fs.outputFile(`fonts/${folder}/style.css`, fonts.map(font => font.fontFace).join('\n')) | |
for (const font of fonts) { | |
const response = await fetch(font.url) | |
const fileData = await response.buffer() | |
const filePath = `fonts/${folder}/${font.filename}` | |
await fs.outputFile(filePath, fileData) | |
console.log(filePath) | |
} | |
} | |
const url = 'https://fonts.googleapis.com/css2?family=Rubik:ital,wght@0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=block' | |
loadFont(url) |
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
{ | |
"name": "download-google-fonts", | |
"version": "1.0.0", | |
"description": "", | |
"main": "index.mjs", | |
"scripts": { | |
"start": "node .", | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"keywords": [], | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"fs-extra": "^9.0.1", | |
"node-fetch": "^2.6.1" | |
} | |
} |
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
npm install | |
npm start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment