It is possible to browse web pages directly from the filesystem. However, Chrome and Firefox have security features that make this inconvenient for development. What we need is a simple static file server. This recipe demonstrates how to install Python (if necessary) and use it to serve files from a directory.
Installing Python, using SimpleHTTPServer to host a local static file server
Getting ready
Find out how to open the command line on your OS. On macOS and Linux, this is called the Terminal. On Windows, it is called the Command Prompt.
You should use a browser that is configured to load ES modules (see the first recipe).
How to do it...
- Check whether you have Python installed already.
- Open the command line.
- Enter the following command:
python --version
- If you see an output like the one displayed as follows, Python is already installed. And you can skip to step 6:
Python 2.7.10
- If you receive an error such as the following, continue with the installation in step 5:
command not found: python
- Install Python on your computer:
- For macOS, download and run the installer for the latest version of Python 2 or 3 from the following link: https://www.python.org/downloads/mac-osx/
- For Windows, download and run the installer for the latest version of Python 2 or 3 from the following link: https://www.python.org/downloads/windows/
- For Linux, use the operating system's built in the package manager to install the Python package
- Create a folder on your desktop named es8-cookbook-workspace.
- Inside the folder, create a text file named hello.txt and save some text to it.
- Open the Command Prompt and navigate to the folder:
- In the Linux or macOS Terminal enter:
cd ~/Desktop/es8-cookbook-workspace
- On Windows type the following command:
cd C:Desktopes8-cookbook-workspace
- Start the Python HTTP server with the following command:
python -m SimpleHTTPServer # python 2
Or we can use following command:
python -m http.server # python 3
- Open your browser and enter the following URL:
http://localhost:8000/.
- You should see a page that shows the contents of the es8-cookbook-workspace folder:
- Click on the link to hello.txt and you'll see the text contents of the file you created.
How it works...
The first thing we did was check if Python was installed. The best way to do this is to ask Python for its version number. This way we know whether Python is installed, and if it's new enough for our purposes.
If it's not installed, Python can be retrieved via the OS's package manager, or via the installers made available through Python's website.
Once installed, Python comes with a lot of utilities. The one we are interested in is the appropriately named SimpleHTTPServer. This utility listens for HTTP requests on port 8000, and returns the contents of the files relative to the directory root. If the path points to a directory, it returns an HTML page that lists the directory contents.