Last active
May 6, 2018 04:48
-
-
Save gyakkun/d2c9704bebb672aae94a32dad090b485 to your computer and use it in GitHub Desktop.
Random picture server.
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 = '/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