Skip to content

Instantly share code, notes, and snippets.

@dzharii
Created February 2, 2021 06:17
Show Gist options
  • Save dzharii/149b514744312124871091509710c848 to your computer and use it in GitHub Desktop.
Save dzharii/149b514744312124871091509710c848 to your computer and use it in GitHub Desktop.
// Usage:
// node randcat.js -p 8765 -- starts http server
// node randcat.js -- generates bookmarklet
if (typeof process !== 'undefined' && process.exit)
(async () => {
const [, , portK, portV] = process.argv;
const mode = (portK === '-p' && portV) ? 'server' : 'bookmarklet';
const fs = require('fs').promises;
let cont = (await fs.readFile(__filename)).toString();
cont = cont.replace(/^.+?(?=\(\(d\) => \{)/s, '');
if (mode === 'server') {
const http = require('http');
console.warn(`Visit us at: http://localhost:${+portV}`);
http.createServer(function (req, res) {
res.write(
`
<html>
<body>
<script>
${cont}
</script>
</body>
</html>
`.trim());
res.end();
}).listen(+portV);
} else {
cont = cont.replace(/(?<!(?:function|typeof|const|let))\s+(?=(?:[^\'"]*[\'"][^\'"]*[\'"])*[^\'"]*$)/gs, '');
console.log('javascript:' + cont);
process.exit(0);
}
})();
else
((d) => {
function update() {
fetch("https://api.giphy.com/v1/gifs/random?api_key=y8CpAcHAapCxnArZIrZHCkSktr8y3IcQ&tag=cat")
.catch(err => console.error('Unable to fetch cats', err))
.then(rsp => rsp.text())
.catch(err => console.error('Unable to get cats response test', err))
.then(txt => JSON.parse(txt))
.catch(err => console.error('Unable to parse cats response json', err))
.then(json => ['data', 'images', 'original', 'url'].reduce((a, n) => a ? a[n] : undefined, json))
.then(url => {
d.body.innerHTML = tmpl(url);
const btnCatz = d.getElementById('catz');
btnCatz.addEventListener('click', update);
});
}
function tmpl(url) {
return [
'<h1>Random Cats</h1>',
'<button id="catz">More Please!</button>',
'<div>',
url ? '<img src="' + url+ '">' : '<p>Failed to load cats</p>',
'</div>'
].join('');
}
d.body = d.createElement('body');
update();
})(typeof document !== 'undefined' ? document : {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment