Create Echo Server in Node.js

Creating HTTP server in Node.js is very simple. In this article we will learn how to create an echo server using Node.js.

Before proceeding, let us understand what an echo server is. In an echo server, the client sends data to the server and the server returns the same data to the server.

echo server

To create an echo server, let us first create a HTTP server. We need to export the HTTP module and then using the createServer function the HTTP server can be created.

var http = require('http');

  http.createServer(function(request,response){    
    
}).listen(8080);

To create the echo server we will work with streams. In Node.js request and response are readable and writeable streams respectively.

Node.js request

A Request is a readable stream with two event data and ends. These events will be used to read data coming from the client. These events can be attached to the request stream as below:

request.on('data',function(message){
          }); 
      request.on('end',function(){
            response.end();
          });

Once we have created a server and attached events to the request, we can write data from the client back to the client by writing a response as below:

  request.on('data',function(message){          
               response.write(message);
          });


Putting the above discussion together, the full source code to create an echo server is as follows:

var http = require('http');
  http.createServer(function(request,response){    
    
      response.writeHead(200);
      request.on('data',function(message){
               response.write(message);
          }); 
      request.on('end',function(){
            response.end();
          });


    }).listen(8080);


So you can run the application on a command prompt using a node as in the following:

run echo server node.js

When the web server is running then using curl the data is post to the server as below. You will get a response back as below:

run echo server node.js1

In the approach above we used data and an end event to echo the data back to the client. Node.js provides another way to write back requested data to the response, using a pipe. You can an create echo server using a pipe as below:

var http = require('http');

  http.createServer(function(request,response){    
    
      response.writeHead(200);
      request.pipe(response);     

    }).listen(8080);

The application above will send data back to the client. In these two ways you can create an echo server in Node.js. I hope you find this article useful. Thanks for reading.

Up Next
    Ebook Download
    View all
    Learn
    View all