Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send data by parts in node.js express

I was searching the web and documentation for node.js express module and it seems there is no way to send data by parts. I have a file rendered not very fast and I want to send parts of it before everything is rendered.

So here are my questions:

  1. Is there a method on response to send data by parts?
  2. What does response.end()?
  3. If there is no way to send data by parts - what is the rationale behind? I would say it looks more blocking than non-blocking if that's true. Browser can load information faster if data is given earlier.

Sample simplified code:

app.get(..) {
  renderFile(file, function(data) {
    response.send(data);
  });
  response.end();
)

This piece of code sends only the first chunk of data. I checked - data is given correctly and callback is called more than one time.

Of course I can append data to the one variable and then write response.send(data); but I don't like this approach - it is not the way it should work.

like image 496
sasha.sochka Avatar asked Jul 14 '13 21:07

sasha.sochka


People also ask

How do you send data in chunks in node JS?

send(data) , it can be called only once. If you are reading and sending a large file, you can stream the file data while being read with res. write(chunk) and on the 'end' event of the file reading, you call res. end() to end the response.

How do I send form data to Express?

To get started with forms, we will first install the body-parser(for parsing JSON and url-encoded data) and multer(for parsing multipart/form data) middleware. var express = require('express'); var bodyParser = require('body-parser'); var multer = require('multer'); var upload = multer(); var app = express(); app.


1 Answers

The response object is a writable stream. Just write to it, and Express will even set up chunked encoding for you automatically.

response.write(chunk);

You can also pipe to it if whatever is creating this "file" presents itself as a readable stream. http://nodejs.org/api/stream.html

like image 197
Brad Avatar answered Sep 19 '22 15:09

Brad