Running a simple web server from a shell

[2015-10-16] dev, javascript, nodejs
(Ad, please don’t block)

The classic command for running a simple web server from a shell is:

python -m SimpleHTTPServer [«port»]

As a result, files are served at http://localhost:«port», with 8000 being the default if you omit the port.

This command has the advantage that it is built into Python and that Python is built into Mac OS X. However, this command always serves the current working directory (the directory that you are currently in), there is no way to provide a directory as an argument. That’s a problem if the directory you want to serve is constantly being deleted and recreated.

Node.js doesn’t have a similar built-in mechanism, but there is an npm package that you can install: http-server.

npm install -g http-server

A basic way of using the shell command that this package comes with is:

http-server [«path»] [-p «port»]

Afterwards, files are served at http://localhost:«port».

  • If you omit the path, ./public is used, if it exists, and ./ otherwise.
  • If you omit the port, 8080 is used.

Why would you want to do this? Many styles of sites and web apps don’t run properly “over” the file: protocol (accessed directly via the local file system). Therefore, you often need to serve them from localhost during development.