Skip to content
Browse files

.functions: Attempt to make `server` open the browser *after* the ser…

…ver has started
  • Loading branch information...
1 parent 390d0fd commit c03c5412fcd38aef2ccb3fd72be34fe2d557d23f @mathiasbynens committed Jul 27, 2012
Showing with 1 addition and 1 deletion.
  1. +1 −1 .functions
2 .functions
@@ -19,7 +19,7 @@ dataurl() {
# Start an HTTP server from a directory, optionally specifying the port
function server() {
local port="${1:-8000}"
- open "http://localhost:${port}/"
+ sleep 1 && open "http://localhost:${port}/" &
# Set the default Content-Type to `text/plain` instead of `application/octet-stream`
# And serve everything as UTF-8 (although not technically correct, this doesn’t break anything for binary files)
python -c $'import SimpleHTTPServer;\nmap = SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map;\nmap[""] = "text/plain";\nfor key, value in map.items():\n\tmap[key] = value + ";charset=UTF-8";\nSimpleHTTPServer.test();' "$port"

3 comments on commit c03c541


This is how I made it open the browser after the server has started:

server() {
    python - "${1:-8000}" <<EOF
import os
import sys
import SimpleHTTPServer
map = SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map
map[""] = "text/plain"
for key, value in map.items():
    map[key] = value + ";charset=UTF-8"
os.system("open http://localhost:" + sys.argv[1])

Doesn’t that still open the browser before the server is started (SimpleHTTPServer.test())? Or in practice, has the server started by the time the browser opened the URL?

I’m not saying the sleep 1-style race condition is any better, just wondering.


Using the function above I've never encountered the browser opening before the server has started, even with a really slow Mac. I think (though I don't have any proof) that the slowness is the Python interpreter starting. By having everything as Python, we bypass that race. I could of course put the os.system last, but I didn't notice any difference doing so.

Please sign in to comment.
Something went wrong with that request. Please try again.