How to send response to a client from node.js custom server

I am using Node-Soap library to call a external web-serivce from my node.js server, code is as shown below:

var http = require("http");
var soap = require("soap");
var url = 'http://www.w3schools.com/webservices/tempconvert.asmx?wsdl';
var args = {Celsius: '40'};

http.createServer(function(request,response) {
  response.writeHead(200,{"Content-Type":"text/html"});
  response.write("<h1>Hello, Web!</h1>");
  soap.createClient(url, function(err, client) { 
    client.CelsiusToFahrenheit(args, function(err, result) {
      console.log(result); //This works
      response.write(result); //This doesn't print
    });
  });
  response.end();
}).listen(8888);

I am able to call web-service successfully and able to get response. The problem is when I print the result using console.log() I am able to get output as:

{ CelsiusToFahrenheitResult: '104' }

But when I send it via response.write, I am not able to get any output, I will get blank values. I tried giving result.toString() and JSON.stringify(result) but still I am getting blank.

Can you please help me? Why I am able to print data using console.log but not using response.write?

You should end the response only after your SOAP request is done (you're ending it immediately after creating the SOAP client, but it might take a while before the result of the SOAP request is available):

http.createServer(function(request,response) {
  response.writeHead(200,{"Content-Type":"text/html"});
  response.write("<h1>Hello, Web!</h1>");
  soap.createClient(url, function(err, client) { 
    client.CelsiusToFahrenheit(args, function(err, result) {
      ...convert result to string-form, perhaps with JSON.stringify()...
      response.end(result);
    });
  });
}).listen(8888);

A few things to note:

  • response.end() can take data as well, so no need (in this case) to use a separate response.write();
  • end() expects the data argument to be a string or a Buffer;