How to install Node.js on Debian 7

nodejs

In this tutorial I’m going to explain how to install Node.js from the scratch. The starting point of this tutorial is a system with a newly installed Debian 7 “wheezy”.

I’m assuming you created a new user during the OS installation. If you didn’t, you will need one. Remember never execute Node.js with root user. If you get hacked the attacker could access to the whole system. For this tutorial you will need insert your user in the sudoers file. If you don’t know how to do it, check this page.

With the terminal, we use this commands:

sudo apt-get install g++ curl libssl-dev apache2-utils

That will install all the dependencies and the compilers. What? Compilers? That’s right, because the best option to install Node.js is from its sources directly. Node.js is a very active project so with this method we assure to get the latest bug fixes and improvements. But where are the sources? The simplest way is GitHub. So execute the following commands to install git on the system:

sudo apt-get install git-core

Now we are ready to download the entire Node.js project from its git source. Create a new folder wherever you want. This folder won’t be necessary after the installation, so it really doesn’t matter where it is. For example, I chose /var/www/ because its empty.

cd /var/www/
sudo git clone git://github.com/joyent/node.git
cd node
sudo ./configure

Finally we can build Node.js as we usually do in Linux. Execute the following command (and go for a good coffee):

sudo make

Just the final step to install it:

sudo make install

Now we can remove the node folder with the installation files:

cd /var/www/
sudo rm -r node

That’s all! Now, optionally, we are going to test if everything is working fine. Create a new app.js file inside your www directory with the following content:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Those aren\'t the droids you\'re looking for\n');
}).listen(8080, "127.0.0.1");
console.log('Magic happens in port 8080');

After create that .js file, we are ready to execute Node.js:

sudo node app.js

Now just enter with your browser in http://127.0.0.1:8080 and you will see a message. Note: If Debian is installed in other network computer, use its IP address instead of 127.0.0.1 in the browser.

I hope you made it! If you have any problem, ask in the comments.

Good coding!

Leave a Reply

Your email address will not be published. Required fields are marked *