Created
October 3, 2012 20:56
-
-
Save rotespferd/3829785 to your computer and use it in GitHub Desktop.
Instant http-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
#!/usr/local/bin/node | |
var http = require('http'), | |
url = require('url'), | |
fs = require('fs'), | |
mime = require('mime'); | |
base = __dirname; | |
http.createServer(function (req, res) { | |
var timer = new Date(); | |
pathname = base + req.url; | |
console.log(pathname); | |
fs.stat(pathname, function(err, stats) { | |
if (err) { | |
res.writeHead(404); res.write('Bad request 404\n'); res.end(); | |
} else if (stats.isFile()) { | |
// content type | |
var type = mime.lookup(pathname); console.log(type); res.setHeader('Content-Type', type); | |
// 200 status - found, no errors res.statusCode = 200; | |
// create and pipe readable stream | |
var file = fs.createReadStream(pathname); file.on("open", function() { | |
file.pipe(res); | |
}); | |
file.on("error", function(err) { | |
console.log(err); | |
}); | |
} else { | |
res.writeHead(403); | |
res.write('Directory access is forbidden'); res.end(); | |
} }); | |
}).listen(3000); | |
console.log('Server running at 3000/'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment