node.js send data to client?

45,771

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);
Share:
45,771

Related videos on Youtube

julian
Author by

julian

Arch Linux + i3wm | Blue MX Keyboard Insanely good software engineer. “Measuring programming progress by lines of code is like measuring aircraft building progress by weight.” - Bill Gates (co-founder of Microsoft) “C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do, it blows away your whole leg.” - Bjarne Stroustrup (Danish computer scientist, developer of the C++ programming language) “Programming is like sex. One mistake and you have to support it for the rest of your life.” - Michael Sinz

Updated on October 11, 2020

Comments

  • julian
    julian over 3 years

    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?

    • Ron van der Heijden
      Ron van der Heijden
      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
  • julian
    julian over 11 years
    Can you read what I wrote please, and tell me what you didn't understand from that?
  • Green
    Green almost 8 years
    Where did you find response.write? There is no any response.write method expressjs.com/en/4x/api.html#res
  • Green
    Green almost 8 years
    Ok, I get it nodejs.org/api/…