Skip to content

Instantly share code, notes, and snippets.

@koenbok
Created September 19, 2012 17:09
Show Gist options
  • Select an option

  • Save koenbok/3750832 to your computer and use it in GitHub Desktop.

Select an option

Save koenbok/3750832 to your computer and use it in GitHub Desktop.
#!/usr/bin/env coffee
http = require("http")
url = require("url")
path = require("path")
fs = require("fs")
# cluster = require("cluster")
port = process.argv[2] or 8888
handleRequest = (request, response) ->
uri = url.parse(request.url).pathname
filename = path.join(process.cwd(), uri)
path.exists(filename, (exists) ->
if uri is "/app.manifest"
modificationTimeSum = 0
response.writeHead(200, "Content-Type": "text/cache-manifest")
response.write("CACHE MANIFEST\n")
addFiles = (relativePath) ->
for file in fs.readdirSync(relativePath)
if file[0] == "."
continue
filePath = path.join(relativePath, file)
if fs.statSync(filePath).isDirectory()
addFiles(filePath)
else
modificationTimeSum += fs.statSync(filePath).mtime.getTime()
response.write("#{filePath}\n")
addFiles(".")
response.write("NETWORK:\n/\n*\n")
response.write("# SUM #{modificationTimeSum}\n")
response.end()
console.log("200 #{uri}")
return
if not exists
response.writeHead(404, "Content-Type": "text/plain")
response.write("404 Not Found\n")
response.end()
console.log("404 #{uri}")
return
if fs.statSync(filename).isDirectory()
filename += "/index.html"
fs.readFile(filename, "binary", (err, file) ->
if err
response.writeHead(500, {"Content-Type": "text/plain"})
response.write("#{err}\n")
response.end()
console.log("500 #{uri}")
return
response.writeHead(200, {"Cache-Control": "public, max-age=3600"})
response.write(file, "binary")
response.end()
console.log("200 #{uri}")
)
)
server = http.createServer(handleRequest)
server.listen(parseInt(port, 10))
# cluster(server).listen(parseInt(port, 10))
console.log("Static file server running at http://localhost:#{port}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment