Created
January 20, 2021 00:47
-
-
Save gyakkun/365868fa24778546aa97c8bac6a9a9b2 to your computer and use it in GitHub Desktop.
random_pic.js
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
var fs = require('fs'), | |
path = require('path'), | |
http = require('http'), | |
url = require('url'); | |
//Params | |
const imageDir = '/here/is/the/random/pictures/' | |
const imageURL = '/pic.jpg'; //The URL you want. | |
const servePort = 8080; //port | |
function getRandFile() { | |
var pics = fs.readdirSync(imageDir); | |
var randomNum = getRandomInt(pics.length); | |
function getRandomInt(max) { | |
return Math.floor(Math.random() * Math.floor(max)); | |
} | |
console.log("The random one is: ", pics[randomNum]); | |
return pics[randomNum]; | |
} | |
http.createServer(function (req, res) { | |
var pathname = url.parse(req.url).pathname; | |
if (pathname == imageURL) { | |
var randImg = imageDir + getRandFile(); | |
res.writeHead(200, { 'Content-Type': 'image/png' }); | |
res.end(fs.readFileSync(randImg)); | |
} else { | |
res.writeHead(404, { "Content-Type": "text/plain" }); | |
res.end("Nothing but chicken!"); | |
} | |
}).listen(servePort); | |
console.log('Server running at http://127.0.0.1:' + servePort + '/'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment