Skip to content

Instantly share code, notes, and snippets.

@mpj
Last active December 12, 2020 00:15
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mpj/6b22ec22a469d785eb399d4b89e540d7 to your computer and use it in GitHub Desktop.
Save mpj/6b22ec22a469d785eb399d4b89e540d7 to your computer and use it in GitHub Desktop.
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
Copy link

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