-
-
Save twolfson/2507569 to your computer and use it in GitHub Desktop.
Quick and dirty file server
This file contains hidden or 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
// Attribution to http://blog.rassemblr.com/2011/04/a-working-static-file-server-using-node-js/ | |
var libpath = require('path'), | |
http = require("http"), | |
fs = require('fs'), | |
url = require("url")/* , | |
mime = require('mime') */; | |
var path = "."; | |
var port = 8080; | |
http.createServer(function (request, response) { | |
var uri = url.parse(request.url).pathname; | |
var filename = libpath.join(path, uri); | |
if (path.indexOf('..') !== -1) { | |
response.writeHead(404, { | |
"Content-Type": "text/plain" | |
}); | |
response.write("404 Not Found\n"); | |
response.end(); | |
return; | |
} | |
libpath.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; | |
} | |
/* var type = mime.lookup(filename); */ | |
response.writeHead(200/* , { | |
"Content-Type": type | |
} */); | |
response.write(file, "binary"); | |
response.end(); | |
}); | |
}); | |
}).listen(port); | |
console.log('Listening at ' + port); |
This file contains hidden or 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
node app.js |
This file contains hidden or 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
node app.js |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment