Created
March 18, 2015 13:18
-
-
Save ctigeek/4a357b0899d20d1d7d85 to your computer and use it in GitHub Desktop.
Simple static 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
| var http = require('http'); | |
| var url = require("url"); | |
| var path = require("path"); | |
| var fs = require('fs'); | |
| http.createServer(function(req, res) { | |
| var uri = url.parse(req.url).pathname; | |
| var filename = path.join(process.cwd(), uri); | |
| if (fs.existsSync(filename)) { | |
| var stats = fs.lstatSync(filename); | |
| if (stats && stats.isFile()) { | |
| try { | |
| console.log("Returning: " + uri); | |
| res.writeHead(200, {'Content-Type':'application/octet-stream','Content-Disposition': 'attachment'}); | |
| var fileStream = fs.createReadStream(filename); | |
| fileStream.pipe(res); | |
| return; | |
| } | |
| catch (err) { | |
| res.writeHead(500, {'Content-Type': 'text/plain'}); | |
| res.write('500 Error: \n' + err.toString()); | |
| res.end(); | |
| return; | |
| } | |
| } | |
| } | |
| console.log("not exists: " + filename); | |
| res.writeHead(404, {'Content-Type': 'text/plain'}); | |
| res.write('404 Not Found\n'); | |
| res.end(); | |
| }).listen(1234); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment