Skip to content

Instantly share code, notes, and snippets.

@judearasu
Created December 1, 2013 18:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save judearasu/7738599 to your computer and use it in GitHub Desktop.
Save judearasu/7738599 to your computer and use it in GitHub Desktop.
Basic static web server with logger using node.js
#!/usr/bin/env node
/**
*
* Basic static web server with logger using node.js.
* Listen on port 8880, IP defaults to 127.0.0.1
*
**/
'use strict';
var http = require("http"),
SSE = require('sse'),
url = require("url"),
path = require("path"),
fs = require("fs"),
port = process.argv[2] || 8880;
var clients = [];
var server = http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), uri);
var now = new Date();
var dateAndTime = now.toUTCString();
var stream = fs.createWriteStream('machine.log', {
'flags': 'a+',
'encoding': 'utf8'
});
path.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.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200);
response.write(file, "binary");
stream.write(dateAndTime + " ", 'utf8');
stream.write(request.headers['user-agent'] + "\n", 'utf8');
stream.write(request.connection.remoteAddress + ": ", 'utf8')
stream.write(request.method + " ", 'utf8')
stream.write(request.url + "\n", 'utf8');
stream.end();
response.end();
});
});
});
/** wraps basic web server in an SSE connection over which file system changes are broadcast */
server.listen(parseInt(port, 10), function () {
var sse = new SSE(server);
sse.on('connection', function (client) { // register watcher when connection starts
clients.push(client);
});
});
/** Log module **/
console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment