|<\/span> sudo -E bash -<\/pre>\n$ sudo apt-get update\r\n$ sudo apt-get install nodejs<\/pre>\nThe nodejs<\/code> package contains both the nodejs<\/code> binary and npm<\/code>, so there is no need to install npm<\/code> separately. But please have in mind that in order for some npm<\/code> packages to work (for example those that require compiling code from source), you will have to install the build-essential<\/code> package:<\/p>\nsudo apt-get install build-essential<\/pre>\nAt this point the Node.js runtime is installed and at the same time prepared to run an application! Let’s write a node.js application.<\/p>\n
<\/span>Create Node.js Application<\/span><\/h2>\nFor now all we write is a Hello World<\/em> application that simply returns “Hello World” to any HTTP requests. This sample application will allow you to get your Node.js set up, which can be replaced with different application – but you need to be sure that your application has been modified to listen on the appropriate IP addresses and ports.<\/p>\nHello World Code<\/h3>\n
The first thing you need to do is to create and open your Node.js application for editing. Here we are using nano<\/code> in order to edit a sample application called hello.js<\/code>:<\/p>\ncd ~\r\nnano hello.js\r\n<\/pre>\nThis following code should be inserted into the file. You can also replace the highlighted port, 8080<\/span><\/code>, in both locations (don`t forget that you should use a non-admin port, i.e. 1024 or greater):<\/p>\n#!\/usr\/bin\/env nodejs\r\nvar http = require('http');\r\nhttp.createServer(function (req, res) {\r\n res.writeHead(200, {'Content-Type': 'text\/plain'});\r\n res.end('Hello World\\n');\r\n}).listen(8080, 'localhost');\r\nconsole.log('Server running at http:\/\/localhost:8080\/');<\/pre>\nNext save and exit.<\/p>\n
The Node.js application listens to the specified address (localhost<\/code>) and port (8080<\/code>), and returns “Hello World” with a 200<\/code> HTTP success code.The remote clients will not have the chance to connect to your application because we are listening on localhost. <\/strong><\/p>\nTest Application<\/h3>\n
If you want to test your application, mark hello.js<\/code> executable:<\/p>\nchmod +x .\/hello.js<\/pre>\nAnd then run it like this:<\/p>\n
.\/hello.js<\/pre>\n