Saturday, 12 March 2016

How to install Node and npm to run node.js programs in Linux


    In one of the previous posts - 
we saw how to install node and npm on widows and also saw running a demo program. In windows it is as simple as downloading the installer and running it. In this post we will see how to install the same in Linux using command line.

Installing Node and NPM on your Linux machine

I am using Ubuntu so I am going to use apt-get to install software’s. You can do the same using yum if you are using fedora or alike.

 First install some of the dependencies that are requied with following command- 

  •  sudo apt-get install python-software-properties python g++ make
Next you will need to add repository to install node and npm from - 
  • sudo add-apt-repository ppa:chris-lea/node.js

Next get an update
  • sudo apt-get update
Now finally install nodejs
  • sudo apt-get install nodejs

This should install both node and npm for you. You can print their version to confirm they are installed -

NOTE : If you see nodejs module installed instead of node then resolve as follows  (May differ across various Ubuntu versions)-

You need to manually create a symlink /usr/bin/node. Shortcut for bash compatible shells:

  • sudo ln -s `which nodejs` /usr/bin/node

Or if you use non-standard shells, just hardcode the path you find with which nodejs:

  • sudo ln -s /usr/bin/nodejs /usr/bin/node

Now lets quickly test it. Create a file called server.js and following contents in it -

 var http = require('http');
 http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
 }).listen(1337, "");
 console.log('Server running at');

Now save it as run it -

You should see following in command promt -

aniket@aniket-Compaq-610:~/programs$ node server.js
Server running at

Now go to browser and hit following url -
You should see - Hello World

That means our server is up and running

Updating Node.Js version

You can use a module called n to upgrade you node package in Mac/Ubuntu

  • sudo npm install -g n
  • sudo n stable

This will install latest stable node package. You can run

  • node --version

If you are still seeing old version it might be directory issues where new package is installed. I had to create a symlink to make it work-

  • sudo ln -s  /usr/local/n/versions/node/9.0.0/bin/node  /usr/local/bin/node

Related Links

No comments:

Post a comment

t> UA-39527780-1 back to top