Skip to content

Instantly share code, notes, and snippets.

@mpj mpj/
Last active Apr 28, 2016

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


node dirtyserve.js

The point your browser to


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.end(filename+' not found')
var contents = fs.readFileSync(filename)
var fileEnding = req.url.match(/\.(.+)$/)[1]
res.writeHead(200, { 'Content-Type': 'text/'+ fileEnding })

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...

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


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'
  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.