Skip to content

Instantly share code, notes, and snippets.

@ctigeek
Created March 18, 2015 13:18
Show Gist options
  • Select an option

  • Save ctigeek/4a357b0899d20d1d7d85 to your computer and use it in GitHub Desktop.

Select an option

Save ctigeek/4a357b0899d20d1d7d85 to your computer and use it in GitHub Desktop.
Simple static file server
var http = require('http');
var url = require("url");
var path = require("path");
var fs = require('fs');
http.createServer(function(req, res) {
var uri = url.parse(req.url).pathname;
var filename = path.join(process.cwd(), uri);
if (fs.existsSync(filename)) {
var stats = fs.lstatSync(filename);
if (stats && stats.isFile()) {
try {
console.log("Returning: " + uri);
res.writeHead(200, {'Content-Type':'application/octet-stream','Content-Disposition': 'attachment'});
var fileStream = fs.createReadStream(filename);
fileStream.pipe(res);
return;
}
catch (err) {
res.writeHead(500, {'Content-Type': 'text/plain'});
res.write('500 Error: \n' + err.toString());
res.end();
return;
}
}
}
console.log("not exists: " + filename);
res.writeHead(404, {'Content-Type': 'text/plain'});
res.write('404 Not Found\n');
res.end();
}).listen(1234);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment