Skip to content

Instantly share code, notes, and snippets.

@dweinstein
Last active August 29, 2015 14:13
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 dweinstein/a4d56d37a178aec27b7a to your computer and use it in GitHub Desktop.
Save dweinstein/a4d56d37a178aec27b7a to your computer and use it in GitHub Desktop.
minimal node js script to serve static file via http

SYNOPSIS

Serve up a single file for all requests to the server.

Usage

./httpServe <path to file>
#!/usr/bin/env node
var http = require("http");
var url = require("url");
var path = require("path");
var fs = require("fs");
var port = 9990;
var filename = process.argv[2] || 'index.html';
var server = http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname;
filename = path.resolve(filename);
console.time('serve');
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()) {
console.log(filename);
throw new Error("directory not supported");
}
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "application/octet-stream"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200);
response.write(file, "binary");
response.end();
console.log(filename)
console.timeEnd('serve');
});
});
});
server.listen(parseInt(port, 10));
server.on('connect', function(req, cltSocket, head) {
});
console.log("serving %s\n => http://localhost:%s \nCTRL + C to shutdown", filename, port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment