Getting Started With Node.js in 5 Minutes*
*It will probably take a bit longer, but at least it is only 5 minutes to read this!
This is a very brief guide of how to set up Node.js and build a very basic webserver using it.
There are already hundreds of guides on the Internet, but this one will focus on setting it up on Ubuntu.
Installation
First, head over to the Node.js website and click the big 'Install' button on the page. This will start a download of it for it (it is only about 150MB).
You need to make sure that you have some other bits installed. Open Terminal and try the following:
apt-get install python
apt-get install g++
apt-get install gcc
If any of them are already installed, it won't do anything. If they are installed, I would suggest doing apt-get update
for each of them. The requirements as I write this are:
- Python 2.6 or 2.7 (careful not to get 3)
- G++ and GCC 4.2 and higher
- GNU Make 3.81 and above
Next, unpackage the downloaded Node package and go to that folder in the terminal.
Next do ./configure
then make
.
This can take a while.
When it is finished do make install
. This can also take a while.
Congratulations, you have now installed Node. You can verify it has been installed by doing node -v
.
Your First Server
Make a new file with a name of your choice (something like app.js) in a location of your choice and open it in a text editor or IDE of your choice.
Put the following code in it (this is taken from the Node.js website):
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Now just go to the terminal and type:
node /path/to/app.js
You should see the words 'Server running at ' printed in the terminal.
If you go to that address in your web browser, you will see Hello World.
There you have it, a Node server set up in no time at all (or should I say "no-de time at all").
Of course, this isn't even the tip of the iceberg of what you can achieve with it, this is one atom of Hydrogen that makes a single frozen water molecule on an iceberg - I will leave you to investigate further on the web.