Skip to content

Instantly share code, notes, and snippets.

@gyakkun
Last active May 6, 2018 04:48
Show Gist options
  • Save gyakkun/d2c9704bebb672aae94a32dad090b485 to your computer and use it in GitHub Desktop.
Save gyakkun/d2c9704bebb672aae94a32dad090b485 to your computer and use it in GitHub Desktop.
Random picture server.
var fs = require('fs'),
path = require('path'),
http = require('http'),
url = require('url');
//Params
const imageDir = '/home/steve/图片/miyamori_avatar/'
const imageURL = '/pic.jpg';
const servePort = 8080;
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