Last active
October 2, 2019 04:31
-
-
Save ryanflorence/3ab921931f8bf1530a68e9651f05a696 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 { createServer } = require('http'); | |
const fs = require('fs'); | |
const path = require('path'); | |
const jokesDir = path.join(__dirname, 'jokes'); | |
const jokes = fs.readdirSync(jokesDir).map(jokeFile => { | |
const jokeData = fs.readFileSync(path.join(jokesDir, jokeFile)); | |
return JSON.parse(jokeData); | |
}); | |
let jokeIndex = -1 | |
createServer((req, res) => { | |
if (req.url === '/joke-me') { | |
// get a request ID so we can see in the console start/end | |
const id = Math.random().toString(32).substr(2,5) | |
// cycle through the jokes | |
jokeIndex = (jokeIndex + 1) % jokes.length | |
const joke = jokes[jokeIndex]; | |
console.log(id, 'started'); | |
// Fake some latency | |
setTimeout(() => { | |
res.writeHead(200, { 'Content-Type': 'application/json' }); | |
res.write(JSON.stringify(joke, null, 2)); | |
res.end(); | |
console.log(id, 'completed'); | |
}, Math.random() * 2000); | |
} else { | |
res.writeHead(404, { "Content-Type": "text/plain" }) | |
res.write("404 Not Found") | |
res.end() | |
} | |
}).listen(5000, () => { | |
console.log('Get a joke! http://localhost:5000/joke-me'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment