Skip to content

Instantly share code, notes, and snippets.

@gyakkun
Created January 20, 2021 00:47
Show Gist options
  • Save gyakkun/365868fa24778546aa97c8bac6a9a9b2 to your computer and use it in GitHub Desktop.
Save gyakkun/365868fa24778546aa97c8bac6a9a9b2 to your computer and use it in GitHub Desktop.
random_pic.js
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