Serving static HTML sites quickly with http-server

Hi guys,

Recently I’ve been involved with front-end development tasks a lot, and with the advance of contemporary front-end philosophies and frameworks such as React and Angular and all, having a quick and painless way to get started with any HTML project (even preferably configuration-less) can be very rewarding at times.

Here in this post I’d love to present my approach:

We’re going to use http-server (if you’re not familiar with front-end development flows using NodeJS and npm, Google shall be your good friend).

While there are a number of static file serving tools ranging from grunt and gulp’s connect & livereload thingies to other node-based software, my favorite so far is http-server because:

  1. it is lightweight enough and simple to use as a CLI.
  2. it has the -P (or --proxy) flag to proxy unhandled (404) requests to another address. This is useful in single-page applications when you want something similar to grunt-connect-proxy yet doesn’t have to be that full-featured or complicated to set up.

So basically, with http-server installed globally, I can just cd into my workdir and run

http-server -p 8080 -c-1

and my HTML site is now served locally on port 8080, without caching (-c-1 means “no cache”), so I can dev all I want without questioning “whether that css file is still cached” 😉

A drawback of this approach is that you don’t get live-reload out of the box, but you can always hook in npm live-reload as a perfect partner-in-crime to http-server.

Where to go from here?

Typing “http-server -p <port> -c-1” a thousand nine hundred and ninety eight times a day sure doesn’t sound fingers’ licking good in the long run, so this is what I added to my ~/.bash_profile:

function serve_fn() {
    if [ -z $1 ]; then
        PORT=8080
    else
        PORT=$1
    fi
    http-server -p $PORT -c-1
}
alias serve=serve_fn

Voila!, from now on I’ll just type “serve” and there it goes. If I have multiple sites that I need to run concurrently, I’ll cd into their respective workdirs and run “serve 8080“, “serve 8081“, and so on.

PS: I wrote to ~/.bash_profile as I’m on a Mac. There should be equivalent solutions for the Windows folks.

UPDATE on 23rd Sep 2015: I also found out an alternative to http-server: live-server. This one has all the good points listed above, plus live-reload feature built-in. You may wanna check it out!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s