Skip to content

Instantly share code, notes, and snippets.

@coolicer
Last active December 20, 2015 21:39
Show Gist options
  • Save coolicer/6199510 to your computer and use it in GitHub Desktop.
Save coolicer/6199510 to your computer and use it in GitHub Desktop.
a very simple static file server made by node.js .
var http = require('http'),
url = require('url'),
path = require('path'),
fs = require('fs');
var PORT = 8080,
mimeTypes = {
"html": "text/html",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"js": "text/javascript",
"css": "text/css",
"txt": "text/plain"
};
var server = http.createServer(function(req,res){
var pathname = __dirname + url.parse(req.url).pathname;
fs.exists(pathname, function(exists){
var fileSteam,
mimeType = mimeTypes[path.extname(pathname).split(".")[1]];
if(!exists){
res.writeHead(404, {"Content-Type": "text/plain"});
res.write('This requst URL ' + pathname + ' was not found on this server.');
res.end();
return;
}
res.writeHead(200,{"Content-Type": mimeType});
fileSteam = fs.createReadStream(pathname);
fileSteam.pipe(res);
});
});
server.listen(PORT);
console.log('Server runing at port: ' + PORT + '.');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment