Skip to content

Instantly share code, notes, and snippets.

@blaquee
Created April 18, 2013 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blaquee/5414009 to your computer and use it in GitHub Desktop.
Save blaquee/5414009 to your computer and use it in GitHub Desktop.
var http = require('http'),
path = require('path'),
fs = require('fs'),
util = require('util');
var extdir = '/extensions';
// create the server
http.createServer(_handleReq).listen(3000);
console.log('Server running, listening on port 3000');
function _handleReq(req, res){
var root = "..",
url = "",
contentType = "text/plain",
filePath = "";
if(req.method !== 'GET'){
res.writeHead(405);
res.end();
return;
}
//ensure we get a file to serve
if( '.' + req.url !== './' ){
filePath = root + extdir + req.url;
path.exists(filePath, serveFile);
} else {
res.writeHead(400);
res.end("Please resquest a file","utf8");
return;
}
function serveFile(file){
if(file === false){
res.writeHead(404);
res.end();
return;
}
var stream = fs.createReadStream(filePath);
//put the file in a stream for network transferring
stream.on('error', function (error) {
res.writeHead(500);
res.end();
return;
});
var mimeTypes = {
'.7z': 'application/x-7z-compressed',
'.zip': 'application/zip'
};
//get the mimeType
contentType = mimeTypes[path.extname(filePath)];
res.setHeader('Content-Type', contentType);
res.writeHead(200);
util.pump(stream, res, function (error) {
//error sending the file
res.end();
return;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment