Skip to content

Instantly share code, notes, and snippets.

@matthewhudson
Forked from ryanflorence/static_server.js
Last active December 15, 2015 08:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewhudson/5229807 to your computer and use it in GitHub Desktop.
Save matthewhudson/5229807 to your computer and use it in GitHub Desktop.
Run a static server from any directory.
http = require 'http'
url = require 'url'
path = require 'path'
fs = require 'fs'
port = process.argv[2] or 8888
headers =
'Content-Type': 'text/plain'
http.createServer( (request, response) ->
uri = url.parse(request.url).pathname
filename = path.join process.cwd(), uri
fs.exists filename, (exists) ->
unless exists
response.writeHead 404, headers
response.write '404 Not Found\n'
response.end()
else
filename += '/index.html' if fs.statSync(filename).isDirectory()
fs.readFile filename, 'binary', (err, file) ->
if err?
response.writeHead 500, headers
response.write err + '\n'
else
response.writeHead 200
response.write file, 'binary'
response.end()
).listen parseInt(port, 10)
console.log 'Static file server running at\n
=> http://0.0.0.0:' + port + '/\nCTRL + C to shutdown'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment