Skip to content

Instantly share code, notes, and snippets.

@william-lohan
Created May 20, 2020 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save william-lohan/57ac3a2fd465382e96ff7d6cae2d1a5a to your computer and use it in GitHub Desktop.
Save william-lohan/57ac3a2fd465382e96ff7d6cae2d1a5a to your computer and use it in GitHub Desktop.
const http = require('http');
const fs = require('fs');
const os = require('os');
const sourceUrl = 'http://pages.cs.wisc.edu/~ballard/bofh/excuses';
const dataFile = `${process.env.APPDATA}\\fun-data`;
function download() {
return new Promise((resolve, reject) => {
http.get(sourceUrl, incoming => {
incoming.on('error', reject);
incoming.pipe(fs.createWriteStream(dataFile)).on('close', resolve);
});
});
}
function dataFileExists() {
return new Promise(resolve => {
fs.exists(dataFile, resolve);
});
}
function readDataFile() {
return new Promise((resolve, reject) => {
fs.readFile(dataFile, (error, data) => {
if (error) {
reject(error);
}
resolve(data.toString());
});
});
}
function pickRandom(array) {
return array[Math.floor(Math.random() * Math.floor(array.length + 1))]
}
(async function () {
if (!await dataFileExists()) {
await download();
}
const data = await readDataFile();
const messages = data.split(/\n/g);
const message = pickRandom(messages);
console.log(message);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment