Skip to content

Instantly share code, notes, and snippets.

@jakeg
Created September 19, 2014 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jakeg/78509d33f593b6bf73ad to your computer and use it in GitHub Desktop.
Save jakeg/78509d33f593b6bf73ad to your computer and use it in GitHub Desktop.
Download all Google fonts using sensible FVD-style names
/*
Script to download all google fonts and name them with FVD-based filenames
- e.g. Rock_Salt.n4.ttf, Open_Sans.i7.ttf
*/
var https = require('https');
var http = require('http');
var fs = require('fs');
var async = require('async');
var key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; // google fonts api server-only key
var fonts = [];
var dir = __dirname + '/fonts/google';
https.get('https://www.googleapis.com/webfonts/v1/webfonts?sort=alpha&key=' + key, function(res) {
var out = [];
res.on('data', function(chunk) {
out.push(chunk);
});
res.on('end', function() {
var json = JSON.parse(out.join(''));
// only fonts with latin character support
json.items.forEach(function(font) {
for (var i=0; i<font.subsets.length; ++i) {
if (font.subsets[i] == 'latin') {
fonts.push(font);
break;
}
}
});
// fonts = [fonts[0]]; // uncomment to debug with just one font
// loop through each font, downloading it. max of 5 families in parallel
async.forEachLimit(fonts, 5, function(font, callback) {
font.variants.forEach(function(variant, i) {
var in_file = font.files[variant];
var out_file = fvdToFilename(googleToFvd(variant, font.family));
console.log(out_file);
var file = fs.createWriteStream(dir + '/' + out_file);
var request = http.get(in_file, function(res) {
res.pipe(file);
res.on('end', function() {
if (i == 0) callback(); // if i==0 otherwise async will get confused surely if multiple variants of the font
});
});
});
});
});
}).on('error', function(e) {
console.log('Error: ' + e.message);
});
// functions
var googleToFvd = function(variant, family) {
var style = variant.match(/[^0-9]+/)||'regular'; // italic, regular/normal (or oblique?)
style = style == 'regular' ? 'n' : (style == 'italic' ? 'i' : 'o');
var weight = variant.match(/[0-9]{1}/)||4; // variant can be e.g. 700italic or italic or 700
return (family ? family + ':' : '') + style + weight;
};
var fvdToFilename = function(fvd) {
return fvd.replace(':', '.').replace(/ /g, '_') + '.ttf';
}
@jakeg
Copy link
Author

jakeg commented Sep 19, 2014

be sure to change the 'key' to your own google fonts API key.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment