You can install Node.js for your platform by visiting http://nodejs.org. Installation is simple and when you are done you will have a node command shell (node) installed as well as the node package manager (npm).
<p> CODE: https://gist.github.com/thec2group-blog/785cf93d277094c37ee1782da5231511.js</p>
<p> CODE: https://gist.github.com/thec2group-blog/46bdd5a89523c0328df4eebd13a9d3b9.js</p>
And when run, this is the obvious result:
<p> CODE: https://gist.github.com/thec2group-blog/672d3399c9120573c9ac9ed1e067aeb7.js</p>
I know what you are thinking, ‘That is cool and all, but it’s hardly a web application’. You are right! Let’s demonstrate something more useful. Node by itself doesn’t do anything right out of the box. But it does come with a set of modules you can use to build up an application. Using a couple of these modules and roughly 15 lines of code, we can create a basic web server.
Here is server.js:
<p> CODE: https://gist.github.com/thec2group-blog/93aa37b2bab921749cac87c5f5760272.js</p>
In this application we are using Node’s http, fs, and path modules and have created an http server that listens on port 8080. Next we look up the requested file (in the same directory as server.js) and if the file is found, we send the html back to the client.
In order to use this, you will need to create some basic html files in the same directory as server.js. Then you can open a new browser window and browse to http://localhost:8080/<your_file>.html.
This is a very basic server with limited error checking, no error handling, and limited functionality. You could spend the time building it out further (and I recommend that you try), but in my next blog we will look at a node package that takes care of all of this for you.
Continue on and read Introduction to Node.js: Part 2.