Leo Jiang
Leo Jiang

Reputation: 26075

How do I send HTML in chunks using Node.js and Express?

I want to send the <head> containing stylesheets before processing the rest of the page. In PHP, I could use ob_flush().

I tried doing something like this:

app.set('view engine','ejs');

app.get('*',function(req,res){
  res.writeHead(200,{'Content-Type':'text/html'});
  res.write('<!doctype...<link rel=stylesheet...');

  doDBStuff()
    .then(function(data){
      res.render('index',{...}); // uses EJS for templating
    });
});

However, the res.render() part does not get sent. Is there a built-in way to send chunked data?

One way to do it would be to manually load the EJS files and manually process them. I would also have to manually send the appropriate headers. I prefer a build-in method if it exists.

Upvotes: 3

Views: 959

Answers (1)

robertklep
robertklep

Reputation: 203231

Here's a simple PoC that does what you want:

var express = require('express');
var app     = express();
var server  = app.listen(3000);

app.set('views', 'views');
app.set('view engine', 'ejs');

app.get('/', function (req, res, next) {
  res.write('<!-- prefix -->');
  setTimeout(function() {
    res.render('index', { ... }, function(err, html) {
      // TODO: handle errors
      res.end(html);
    });
  }, 1000);
});

Note that it uses the "callback variant" of res.render(), which can be used to just render a template without sending back a response (if you don't do it this way, res.render() will generate an error). Alternatively, you can use app.render() which does the same.

Upvotes: 5

Related Questions