Geographic chat app with Node.js, Socket.IO, and Google Maps - Part one
In this series of posts we are going to show you how to use node.js and Socket.IO to build a simple chat application, and then mix it up with Google Maps and the Geolocation API to create a cool geographic app. We will use Bootstrap with a modified css to get a nice look for the website.
Node.js is a great platform for building event based applications, if you haven't heard about it or want to get hands on work you may want to check out nodemanual.org, its short tutorials provide a good introduction of how node.js works.
In this post we will show you how to use Node.js as a simple web server. In a future post we will show you how to build the same application with the express framework, which provides a nice and thin layer of features on top of node, but this time we will do it by hand.
Let's get started! Create a text file with the name 'app.js' to start coding. First we need to include the modules that our server is going to use, which in node.js is done with the
Next we create the server, passing the function that handles the HTTP requests as an argument.Then we obtain the name of the file we need to return from the request, and set a default file for the root ("/index.html"). After that we check if the file exists inside a 'public' folder located in the same directory of the script, returning a 404 response in case the file does not exist.
If the file exists, we obtain its MIME type with help of the node-mime plugin and prepare a read stream to asynchronously write chunks of the file to the response, avoiding the server to block on the IO reading operation.
There you go, we have a working web server! Right? Ehm, not yet. We need the server to open a port so it can listen to requests. Add this line at the bottom of your script.
Make sure you have a 'public' folder in the same directory where you saved the script and put an 'index.html' with the content of your choice. Next open a terminal and type:Now we're ready! You can test if the server is working by opening a tab in your browser at 'localhost:8080'.
Now that we have a basic web server we can start building the chat application, in the following posts we will show you how to use Socket.IO to send chat messages and geographic updates in real time. If you are impacient and can't wait for the next post you can try our live demo!
Check out the next posts in this series: