Created
May 20, 2020 21:34
-
-
Save william-lohan/57ac3a2fd465382e96ff7d6cae2d1a5a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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