While installing node.js from the repository it often installs old version of the software. It’s best to update the software repository using-
$ sudo apt-get update
If the above commands does not provide you with the latest software then use-
$ curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash
Now install Node.js-
$ sudo apt-get install nodejs
$ check version - nodejs -v
This will install latest stable version of Node.js.
Now install npm.
NPM is node package manager for Node.js NPM installs a Node.js modules from the repository and also create package.json file to maintain the list of modules installed in the application. This is very similar to using composer to install Drupal modules.
$ sudo apt-get install npm
Running your first code for testing
Create a node.js file- vi nodejstest.js
Add the following code-
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');
In the shell execute the file as- $ nodejs nodejstest.js
You should see an output on the shell-
Server running at http://127.0.0.1:3000/
Now you can open the browser and see the output-
http://127.0.0.1:3000/ or http://localhost:3000/