How to turn any Mac folder into a Web Server

When developing client side JavaScript it’s handy to create files in a temp directory to test ideas. You don’t have to worry about deploying to a server or corrupting an existing site.  On a Mac you can turn any folder into a Web server by simply opening up a terminal window and typing a command.  In this tutorial I’ll show you how to do that.

On a Mac open up a Terminal Window and do the following:

  1. Create a test folder:  mkdir test
  2. Change to that folder: cd test

Create a JavaScript file

  1. Create a new text file in that folder called message.js
  2. Add the text below to that file and save it:
function ShowMessage(msg) {
  var now = new Date();
  document
    .getElementById("message")
    .innerHTML = now + "<br />" + msg;
}

Create an HTML file

  1. Create a new text file in that folder called index.html
  2. Add the text below to that file and save it:
<html>
  <header>
    <title>Message Test</title>
    <script 
      src="message.js" 
      type="text/javascript"/>
    </script>
   </header>
 <body>
   <input 
     type="button" 
       onclick="ShowMessage('Hello World!')" 
       value="Display Message" />
   <hr size="1" />
   <div id="message"></div>
   <hr size="1" />
 </body>
</html>

Start the Web Server

In the folder where you just created those files type the following:

python -m SimpleHTTPServer 8000

If you get an already in use error, try a different port number (like 8001).

  1. In a Web browser on the same machine browse to: http://localhost:8000
  2. Press the button to generate a message
  3. Press the button again to generate a message with a new timestamp

Mitch Allen is a game developer and tech writer. To download his latest games and books please visit his Web site at mitchallen.com