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?

1
  • 1
    Basicly i would choose for sockets. Like 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 Commented Feb 17, 2013 at 2:33

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Can you read what I wrote please, and tell me what you didn't understand from that?
Where did you find response.write? There is no any response.write method expressjs.com/en/4x/api.html#res
Ok, I get it nodejs.org/api/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.