node dirtyserve.js
The point your browser to
http://localhost:3000/myfile.xxx
and the server will try to serve that file from the local server.
var http = require('http') | |
var fs = require('fs') | |
http.createServer(function (req, res) { | |
var filename = req.url.substring(1) | |
if (!fs.existsSync(filename)) { | |
res.writeHead(404) | |
res.end(filename+' not found') | |
return | |
} | |
var contents = fs.readFileSync(filename) | |
var fileEnding = req.url.match(/\.(.+)$/)[1] | |
res.writeHead(200, { 'Content-Type': 'text/'+ fileEnding }) | |
res.end(contents) | |
}).listen(3000) |
I use Nodejs quick and dirty static web server like yours everyday.
Usually I prefer to pipe a read stream inside the response to avoid IO blocking operations
It would also be a good idea to handle request to "/" by linking to an index.html file and redirect each request inside a sub folder named "public" to avoir expose everything including your application code.
I use the split function to remove any querystring that could follow the filename in the url.
That could be some nice addition to your code.