Skip to content

Instantly share code, notes, and snippets.

@mpj mpj/README.md
Last active Apr 28, 2016

Embed
What would you like to do?
REALLY quick and dirty static file dev server

Usage

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)
@Elanouette

This comment has been minimized.

Copy link

commented Apr 28, 2016

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

var file = fs.createReadStream(url)

file.on('error', function(err){
  // Code...
  res.end()
});

file.on('end', function(){
  res.end()
})

file.pipe(res)

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.

var url = __dirname

if(req.url == "/"){
  url += '/public/index.html'
}else{
  url += '/public'+ req.url.split("?")[0]
}

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.