Create a nodejs server

What is node.js?

Node.js is a server-side platform built on Google Chrome's Javascript Engine (V8 Engine). Nodejs is is a platform built on Crome's javascript Runtime for easily building fast and scalable network applications.

Nodejs uses a single-threaded model with an event looping  Event mechanism that helps the server to respond in a non-blocking way and makes the server highly scalable as to traditional server which creates limited threads to handle requests.  Nodejs uses a single-threaded program and the same program can provide service to an as much larger number of requests than traditional servers like APACHE HTTP Server.

Where to use node.js


The following are the areas where node.js is providing itself as a perfect technology partner.

  • Data Streaming Applications
  • Single-page Applications
  • API based Applications
  • I/O bound Applications
Moreover, it is not advisable to use Nodejs for CPU intensive applications.

Create node.js server

Creating a node.js server consist of the following -
  1. Import required modules
  2. create server
  3. Read requests and respond to the request.

Let us see node.js in action with a practical example.

touch nodeapp.js

The above command will create a file call [nodeapp.js] on a terminal. Or you can just click on new
file and create a new file.
Inside the file [nodeapp.js], we start with requiring Http.
var http  = require('http');

Next, we will use the required Http instance and call the create server method.
var http  = require('http');

http.createServer((requestresponse)=> {
    // send http header , status code:200 : ok and type
    response.writeHead(200, {'Content-type': 'text/plain'});

    // send the response body as "Hello World"
    response.end("Hello world\n");
}).listen(8888);

// print server information
console.log("Server running on port 8888");

Next, we will run our server with the following command.
node nodeapp.js
Server running on port 8888


Verify the output [server running on port 8888]
Next, we need to test our server. Enter the following address on your browser and it will send a request to our newly created server and we expect our server to respond with a message.
http://localhost:8888

we got the message [Hello World] on the browser as expected.

If you find it helpful, please shares...
Next, I will be giving a clear and practical example of nodejs callback concept.

Post a Comment

1 Comments