Saturday, 1 April 2017

How to Install and Run Node.js on Ubuntu

What is Node.js?
Allows you to build scalable network applications using JavaScript on the server-side.

What could you Build?
  • Websocket Server
  • Fast File Upload Client
  • Ad Server
  • Any Real-Time Data Apps

Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.

Download the Node.js Linux package here

Open terminal and go to Downloads Folder



Extract the tar.xz file


Move the extracted file to the folder node


Move the folder node to the opt folder in the Linux file system. Then go to bin folder, you will see two folders node and npm







Configure the node, nodejs & npm as per the following commands





The node has been installed now, check the version


How to run the Hello World Program in nodejs?


Make a directory to store the files of the program. Go to the testapp directory and run the npm init command. Just enter until the prompt appear.



Create a file named server.js in the testapp folder and copy the following code.

const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});
server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Run the server.js file



Test the app with the port number.

FAQ on Node.js

  1. Is Node.js really Single-Threaded?
  2. Explain the Asynchronous approach in Node.js?
  3. What is global in Node.js?
  4. What is the use of underscore in Node.js?
  5. Can you create HTTP server in Node.js?
  6. How to load HTML in Node.js?



No comments:

Post a Comment