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

Before we move ahead, let us understand what an echo server is. In echo server, client sends data to server and server returns back same data to server.

image

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


var http = require('http');

http.createServer(function(request,response){

}).listen(8080);

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

image

Request readable stream got two events data and end. These events will be used to read data coming from client. These events can be attached to request stream as below,


request.on('data',function(message){

 });

 request.on('end',function(){

 response.end();
 });

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


request.on('data',function(message){

 response.write(message);

 });

Putting above discussion together full source code to create 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 application on command prompt using node

clip_image001

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

clip_image002

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


var http = require('http');

http.createServer(function(request,response){

 response.writeHead(200);
 request.pipe(response);

}).listen(8080);


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

Advertisements

4 thoughts on “Create Echo Server in Node.js

  1. Pingback: TechNet Blogs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s