Run a web server from any folder

By

Learn how to spin up a quick local web server from any folder using http-server with Node.js, Python http.server, or PHP's built-in php -S command.

~~~

You can run a web server from any folder on your system with a single command. Node.js, Python and PHP all give you one, so whatever language you already have installed, you’re covered.

This is a common need. You have absolutely no time to configure a proper web server like Apache or Nginx, because this is just for a few minutes, or for testing your app.

Why not just double-click the HTML file and open it in the browser? Because pages loaded from file:// URLs run with restrictions. fetch() calls to local files fail, and ES modules won’t load. A local server serves everything over http://localhost, the way a real server would.

Let’s see the options, depending on the language you prefer.

Node.js

If you use Node.js and you have installed npm already, run

npm install -g http-server

and then run http-server in the folder you want to expose through your server.

By default it will start the server on port 8080, but you can change it using the -p flag (see more options by running http-server --help).

Alternatively, you can skip the global install and run it directly with npx:

npx http-server

npx downloads the package if needed and runs it, so nothing stays installed on your machine.

Python

If you use Python and have it installed, just run

python -m SimpleHTTPServer 8080

(Python 2)

or

python -m http.server 8080

(Python 3)

to start a local server on port 8080.

Python comes preinstalled on macOS and most Linux distributions, so this is often the zero-setup option. On many systems the Python 3 executable is called python3, so if the command above complains, try python3 -m http.server 8080.

PHP

If you use PHP and you run a modern version of it, run

php -S localhost:8080

This is the built-in development server. It’s meant for testing, not production, but for a quick local check it’s all you need.

If the port is already taken

One error you’ll hit sooner or later: you start a server and get something like EADDRINUSE (Node) or Address already in use (Python).

It means another process is already listening on that port, probably a server you started earlier and forgot about. Pick a different port, like 8081, or find and stop the old process. Ports below 1024 also require root, so stick with high numbers like 8080.

Tagged: Node.js · All topics
~~~

Related posts about node: