How to create a localhost server?

I’m working on HTML5 games for the time being. During that I came across a very basic issue. If you want to test your HTML5 game in your local system, well you can’t. At least not directly.

In almost all projects, your main HTML file would have to access some other local file like a game.js javascript file from your local system. This is a huge security issue in the eyes of Webkit based browsers like Chrome and Safari. It is, kind of. Imagine some random person in the internet writes an extension which can access your local file without your permission and take it away. I don’t know why Firefox still allows this.

Our aim is not to hack, not now anyway. We just want to test a game. One way to overcome the issue is to create a server in your system itself. That way, the rules of the internet will be followed even if you are opening a file in your system.

… enter localhost…

A localhost is basically just a domain which points to your computer itself. You can create a localhost using many ways. You can use programs like XAMPP and LAMP in Windows and Linux respectively to do this. You can also seek the help of nodejs and install a module called http-server and start a localhost.

But there’s a way more simple and robust trick to create a localhost than all of the above. We are still on the testing phase of our game anyway. Most of you might have Python installed in your system. (If not, install it from here and refresh this page). Python also allows us to run modules just like nodejs and it comes pre-installed with some. http-server is one of them. You can call the module from the command line by passing the argument -m.

The full command is like this:

python -m http.server

Or if you are using Python2.7:

python -m SimpleHTTPServer

The port number is by default 8000. You can pass a different port number like this:

python -m http.server 8080

Now the question is, where is the localhost now? Where does it point to? It is wherever you called the python command from. So if you want to run your game on localhost, you might have to run this command from the folder where your main HTML file is located.

That’s it! Enjoy your coding.

Love. Peace.