Created
October 18, 2013 07:08
-
-
Save smolnikov/7037596 to your computer and use it in GitHub Desktop.
Node.js static web-server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'), | |
url = require('url'), | |
path = require('path'), | |
fs = require('fs'), | |
dirpath = './' + (process.argv[2] || ''), | |
port = process.argv[3] || 8888; | |
var server = http.createServer(function(request, response) { | |
var uri = url.parse(request.url).pathname, | |
filepath = path.resolve(dirpath, uri.substring(1, uri.length)); | |
//console.log(uri + ' > ' + filepath); | |
fs.exists(filepath, function(exists) { | |
if (!exists) { | |
response.writeHead(404, { 'Content-Type': 'text/html'}); | |
response.write('<!doctype html><meta charset="utf8">'); | |
response.write('<h1>404</h1>'); | |
response.write('<a href="/">Back to root</a>'); | |
response.end(); | |
return; | |
} | |
if (fs.statSync(filepath).isDirectory()) { | |
fs.readdir(filepath, function(err, files) { | |
response.writeHead(200, {'Content-Type': 'text/html'}); | |
response.write('<!doctype html><meta charset="utf8">'); | |
response.write('<h1>' + request.url + '</h1>'); | |
if(request.url != '/') | |
{ | |
response.write('<a href="' + path.resolve(request.url, '..') + '">..</a><br/>'); | |
} | |
else | |
{ | |
response.write('..<br/>'); | |
} | |
files.forEach(function(file) { | |
response.write('<a href="' + path.join(request.url, file) + '">' + file + '</a><br>'); | |
}); | |
response.end(); | |
}); | |
return; | |
} | |
fs.readFile(filepath, "binary", function(error, file) { | |
if(error) { | |
response.writeHead(500, {'Content-Type': 'text/html'}); | |
response.write('<!doctype html><meta charset="utf8">'); | |
response.write('<h1>500</h1>'); | |
response.write('<a href="/">Back to root</a>'); | |
response.end(); | |
return; | |
} | |
response.writeHead(200); | |
response.write(file, 'binary'); | |
response.end(); | |
}); | |
}); | |
}); | |
server.listen(parseInt(port, 10)); | |
console.log('\nStatic file server running at\n http://localhost:' + port + '/\n'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment