Node.js First Example

There can be console-based and web-based node.js applications.

Node.js console-based Example

File: console_example1.js

  1. console.log('Hello welookupst');   

Open Node.js command prompt and run the following code:

  1. node console_example1.js  

Here, console.log() function displays message on console.

Node.js web-based Example

A node.js web application contains the following three parts:

  1. Import required modules: The "require" directive is used to load a Node.js module.
  2. Create server: You have to establish a server which will listen to client's request similar to Apache HTTP Server.
  3. Read request and return response: Server created in the second step will read HTTP request made by client which can be a browser or console and return the response.

How to create node.js web applications

Follow these steps:

  1. Import required module: The first step is to use ?require? directive to load http module and store returned HTTP instance into http variable. For example:
    1. var http = require("http");  
  2. Create server: In the second step, you have to use created http instance and call http.createServer() method to create server instance and then bind it at port 8081 using listen method associated with server instance. Pass it a function with request and response parameters and write the sample implementation to return "Hello World". For example:
    1. http.createServer(function (request, response) {  
    2.    // Send the HTTP header   
    3.    // HTTP Status: 200 : OK  
    4.    // Content Type: text/plain  
    5.    response.writeHead(200, {'Content-Type': 'text/plain'});  
    6.    // Send the response body as "Hello World"  
    7.    response.end('Hello World\n');  
    8. }).listen(8081);  
    9. // Console will print the message  
    10. console.log('Server running at');  
  3. Combine step1 and step2 together in a file named "main.js".
  4. File: main.js

    1. var http = require("http");  
    2. http.createServer(function (request, response) {  
    3.  // Send the HTTP header   
    4.    // HTTP Status: 200 : OK  
    5.    // Content Type: text/plain  
    6.    response.writeHead(200, {'Content-Type': 'text/plain'});  
    7.    // Send the response body as "Hello World"  
    8.    response.end('Hello World\n');  
    9. }).listen(8081);  
    10. // Console will print the message  
    11. console.log('Server running at');  

How to start your server:

Node.js first example 3

Now server is started.

Make a request to Node.js server:

Open in any browser. You will see the following result.


welookups is optimized for learning.© welookups. 2018 - 2020 All Right Reserved and you agree to have read and accepted our term and condition.