Skip to content

Instantly share code, notes, and snippets.

@oatmealine
Created October 15, 2020 01:31
Show Gist options
  • Save oatmealine/780d142166a8ca0e91ae4db568161016 to your computer and use it in GitHub Desktop.
Save oatmealine/780d142166a8ca0e91ae4db568161016 to your computer and use it in GitHub Desktop.
const got = require('got');
const fs = require('fs');
const os = require('os');
const { exec } = require('child_process');
const api = `http://images.ucomics.com/comics/ga`;
const startDate = new Date('19 June 1978 00:00:00 GMT');
function generateComicURL(date) {
// http://images.ucomics.com/comics/ga/2000/ga001231.gif
let day = String(date.getDate()).padStart(2, '0');
let month = String(date.getMonth() + 1).padStart(2, '0');
let year = String(date.getFullYear());
return `${api}/${year}/ga${year.slice(2, 4)}${month}${day}`;
}
function randomComic() {
let ms = startDate.getTime() + Math.random() * (Date.now() - startDate.getTime());
return generateComicURL(new Date(ms));
}
function renderComic(data, format) {
let file = `${os.tmpdir}/garfield.${format}`;
fs.writeFileSync(file, data);
exec(`viu -s -t ${file}`, (stdout, stderr) => {
console.log(stderr || stdout);
fs.unlinkSync(file);
});
}
async function fetchComic(url) {
let data;
let format;
try {
data = await got(`${url}.gif`);
format = 'gif';
} catch(_) {
data = await got(`${url}.jpg`);
format = 'jpg';
}
return [data.rawBody, format];
}
async function renderRandomComic() {
let comic = randomComic();
let res = await fetchComic(comic);
renderComic(res[0], res[1]);
}
renderRandomComic();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment