3

I wonder how can I send data from node.js to client?

example node.js code -

var http = require('http');

var data = "data to send to client";

var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
}).listen(8125);

Now, I want to send the data variable to client and log it with JavaScript..
How can I do that?

Thanks ;)

EDIT: Does anyone know how to send array?

Mujtaba Zaidi
  • 629
  • 1
  • 6
  • 14
julian
  • 4,634
  • 10
  • 42
  • 59
  • 1
    Basicly i would choose for sockets. Like [socket.io](http://socket.io/). That way you can communicate via the socket from client to server and from server to client. Common used for realtime chat applications – Ron van der Heijden Feb 17 '13 at 02:33

1 Answers1

6

If You Want to do it after response.end you should use Socket.io or Server Send Events.

If you want it before res.end, you would make your code look like:

var http = require('http');

var data = "data to send to client";

var server = http.createServer(function (request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write(data); // You Can Call Response.write Infinite Times BEFORE response.end
    response.end("Hello World\n");
}).listen(8125);
Ari Porad
  • 2,834
  • 3
  • 33
  • 51
  • Can you read what I wrote please, and tell me what you didn't understand from that? – julian Feb 17 '13 at 01:37
  • Where did you find `response.write`? There is no any `response.write` method http://expressjs.com/en/4x/api.html#res – Green Sep 03 '16 at 06:38
  • Ok, I get it https://nodejs.org/api/http.html#http_response_write_chunk_encoding_callback – Green Sep 03 '16 at 06:43