Skip to content

Commit

Permalink
.functions: Attempt to make server open the browser *after* the ser…
Browse files Browse the repository at this point in the history
…ver has started
  • Loading branch information
mathiasbynens committed Jul 27, 2012
1 parent 390d0fd commit c03c541
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion .functions
Expand Up @@ -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"
Expand Down

3 comments on commit c03c541

@sindresorhus
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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])
SimpleHTTPServer.test()
EOF
}

@mathiasbynens
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@sindresorhus
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.