|
const http = require('http'); |
|
const fs = require('fs'); |
|
const path = require('path'); |
|
const PORT = process.env.PORT || 8125; |
|
|
|
http.createServer(function (request, response) { |
|
logRequest(request); |
|
|
|
var filePath = '.' + request.url; |
|
if (filePath == './') { |
|
filePath = './index.html'; |
|
} |
|
|
|
var extname = path.extname(filePath); |
|
var contentType = 'text/html'; |
|
switch (extname) { |
|
case '.js': |
|
contentType = 'text/javascript'; |
|
break; |
|
case '.css': |
|
contentType = 'text/css'; |
|
break; |
|
case '.json': |
|
contentType = 'application/json'; |
|
break; |
|
case '.png': |
|
contentType = 'image/png'; |
|
break; |
|
case '.jpg': |
|
contentType = 'image/jpg'; |
|
break; |
|
case '.wav': |
|
contentType = 'audio/wav'; |
|
break; |
|
case '.ipa': |
|
contentType = 'application/octet-stream'; |
|
break; |
|
case '.plist': |
|
contentType = 'text/xml'; |
|
break; |
|
} |
|
|
|
fs.readFile(filePath, function (error, content) { |
|
if (error) { |
|
if (error.code == 'ENOENT') { |
|
fs.readFile('./404.html', function (error, content) { |
|
response.writeHead(200, { |
|
'Content-Type': contentType |
|
}); |
|
response.end(content, 'utf-8'); |
|
}); |
|
} else { |
|
console.log('error', error) |
|
response.writeHead(500); |
|
response.end('Sorry, check with the site admin for error: ' + error.code + ' ..\n'); |
|
response.end(); |
|
} |
|
} else { |
|
response.writeHead(200, { |
|
'Content-Type': contentType |
|
}); |
|
response.end(content, 'utf-8'); |
|
} |
|
}); |
|
|
|
}).listen(PORT); |
|
console.log('Server running', `http://localhost:${PORT}/`); |
|
|
|
function logRequest(request) { |
|
const ip = request.headers['x-forwarded-for'] || request.socket.remoteAddress || null; |
|
const path = request.url |
|
const method = request.method; |
|
const timeStamp = getTimeStamp(); |
|
console.log('log:', timeStamp, method, path, 'from ip', ip); |
|
} |
|
|
|
function getTimeStamp() { |
|
var today = new Date(); |
|
var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate(); |
|
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds(); |
|
return date + ' ' + time; |
|
} |