Created
August 18, 2015 21:03
-
-
Save KlonD90/9ebb77cc662a2b109b8e to your computer and use it in GitHub Desktop.
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 http = require('http'); | |
var fs = require('fs'); | |
var checkFile = function(file){ | |
return new Promise(function(resolve, reject){ | |
fs.exists(file, function(exists){ | |
resolve(exists); | |
}); | |
}); | |
} | |
function getFileNameFromUrl(url){ | |
var tmpUrl = url.trim().substr(1); | |
//strip some dots info for secure | |
tmpUrl = tmpUrl.replace(/\.\.\//g, ''); | |
if (tmpUrl.indexOf('?')>=0) | |
return tmpUrl.substr(0, tmpUrl.indexOf('?')); | |
else | |
return tmpUrl; | |
} | |
function getFileExtensionFromName(filename){ | |
return filename.split('.').pop(); | |
} | |
var mimeTypeMap = { | |
'css': 'text/css', | |
'js': 'application/javascript', | |
'html': 'text/html' | |
}; | |
var server = http.createServer(function(req, res){ | |
var url = req.url; | |
var fileName = getFileNameFromUrl(url); | |
var filePath = './static/'+fileName; | |
checkFile(filePath). | |
then(function(check){ | |
if (!check) | |
{ | |
var body = 'File not found'; | |
res.writeHead(404, | |
{ | |
'Content-length':body.length, | |
'Content-type': 'text/plain' | |
} | |
); | |
return void res.end(body); | |
} | |
var extension = getFileExtensionFromName(fileName); | |
if (mimeTypeMap[extension]) | |
{ | |
res.writeHead(200, | |
{ | |
'Content-type': mimeTypeMap[extension] | |
} | |
); | |
} | |
var fileStream = fs.createReadStream(filePath); | |
fileStream.pipe(res); | |
}) | |
}); | |
server.listen(5300); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment