Skip to content

Instantly share code, notes, and snippets.

@pulsedemon
Created August 27, 2013 20:18
Show Gist options
  • Save pulsedemon/6358596 to your computer and use it in GitHub Desktop.
Save pulsedemon/6358596 to your computer and use it in GitHub Desktop.
my first node.js server
var http = require('http')
, url = require("url")
, path = require("path")
, fs = require('fs')
, mime = require('mime')
;
var server = http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), uri)
, baseUrl = (uri.substr(-1, 1) == '/') ? uri : uri + '/'
;
console.log('URI requested: ', uri);
var fileExists = false;
fs.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
// If thq request uri is a directory,
// try and load index.html. If one doesn't exist
// create a directory listing
if (fs.statSync(filename).isDirectory()) {
filename += 'index.html';
fs.exists(filename, function(exists) {
if (!exists) {
console.log('File not found: ', filename);
console.log('Building directory listing...');
filename = filename.replace('index.html', '');
fs.readdir(filename, function (err, files) {
if (err) {
throw err;
}
response.writeHead(500, { 'content-type': 'text/html' });
files.map(function (file) {
return path.join(filename, file);
}).filter(function (file) {
return fs.statSync(file).isFile();
}).forEach(function (file) {
console.log("%s (%s)", file, path.extname(file));
response.write('<a href="' + baseUrl + path.basename(file) + '">' + path.basename(file) + '</a><br>');
});
response.end();
return;
});
}
else {
fileExists = true;
}
});
}
else {
fileExists = true;
}
// if the request is for a file that exists, load it
if (fileExists) {
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, { 'content-type': 'text/plain' });
console.log('error')
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200, {"content-type": mime.lookup(path.basename(filename))});
response.write(file, "binary");
response.end();
});
}
});
});
server.listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment