Skip to content

Instantly share code, notes, and snippets.

@serverwentdown
Forked from ryanflorence/static_server.js
Last active December 26, 2015 14:43
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save serverwentdown/9304183 to your computer and use it in GitHub Desktop.
Save serverwentdown/9304183 to your computer and use it in GitHub Desktop.
Node.JS static file web server. Put it in your path to fire up servers in any directory, takes an optional port argument. (Modded for larger files)
var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs")
port = process.argv[2] || 4002;
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname
, filename = decodeURIComponent(path.join(process.cwd(), uri));
console.log(uri);
fs.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
if (fs.statSync(filename).isDirectory()) filename += '/index.html';
fs.exists(filename, function(exists) {
if (!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("No index.html file. \n");
response.end();
return;
}
var readstream = fs.createReadStream(filename);
response.writeHead(200);
// readstream.setEncoding("binary");
readstream.pipe(response);
// readstream.on('data', function (chunk) {
// response.write(chunk, 'binary');
// });
// readstream.on('end', function () {
// console.log('served ' + filename + '');
// response.end();
// });
readstream.on('error', function(err) {
response.write(err + "\n");
response.end();
return;
});
});
});
}).listen(parseInt(port, 10));
console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");
@sashuk
Copy link

sashuk commented May 25, 2015

Thanks a lot for the gist!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment