From d271737f07fd20553d4a291c719809915525edd1 Mon Sep 17 00:00:00 2001 From: Henrique Dias Date: Sun, 3 Nov 2019 09:10:04 +0000 Subject: [PATCH] feat: download high resolution imgs (#6) License: MIT Signed-off-by: Henrique Dias --- lib/xkcd.js | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/lib/xkcd.js b/lib/xkcd.js index 335fe34..e34ffb3 100644 --- a/lib/xkcd.js +++ b/lib/xkcd.js @@ -1,4 +1,5 @@ const fetch = require('node-fetch') +const path = require('path') async function getLatestId () { const raw = await fetch(`https://xkcd.com/info.0.json`) @@ -6,10 +7,26 @@ async function getLatestId () { return data.num } +async function getImage (url) { + const ext = path.extname(url) + const url2x = `${path.dirname(url)}/${path.basename(url, ext)}_2x${ext}` + + let res = await fetch(url2x) + if (!res.ok) { + res = await fetch(url) + } + + if (!res.ok) { + throw new Error('bad image request') + } + + return res.buffer() +} + async function getComic (id) { const raw = await fetch(`https://xkcd.com/${id}/info.0.json`) const data = await raw.json() - const img = await (await fetch(data.img)).buffer() + const img = await getImage(data.img) return { data, img } }