how to communicate between two node.js instances, one client one server


I am a beginner in node.js (infact started just today). One of the basic concepts is not clear to me, which I am asking here & couldn't find on SO.

Reading some tutorials on the web I wrote a client side & a server side code:

Server side (say server.js):

var http = require('http'); //require the 'http' module

//create a server
http.createServer(function (request, response) {
  //function called when request is received
  response.writeHead(200, {'Content-Type': 'text/plain'});
  //send this response
  response.end('Hello World\nMy first node.js app\n\n -Gopi Ramena');
}).listen(1337, '');

console.log('Server running at');

Client side (say client.js):

var http=require('http');

//make the request object
var request=http.request({
  'host': 'localhost',
  'port': 80,
  'path': '/',
  'method': 'GET'

//assign callbacks
request.on('response', function(response) {
   console.log('Response status code:'+response.statusCode);

   response.on('data', function(data) {
     console.log('Body: '+data);

Now, to run the server, I type node server.js in the terminal or cmd prompt. & it runs successfully logs the message in the console & also outputs the response when I browse to

But, how to I run client.js? I could not understand how to run the client side code.

2/12/2016 8:45:43 AM

Accepted Answer

Short answer: you can use the command

node client.js

to run your "client side" code, it will send one http request

Regarding to what's server side and what's client side, it's really depends on the context.

Although in most cases, client side means the code running on your browser or your mobile phone app, server side means the "server" or "back end" your browser or your mobile phone is talking to.

In your case, I think it's more like one "server" talks to another "server", and they are both on the back end, since that's what node.js is designed for

6/18/2012 7:01:30 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow