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

I want to submit <head>

the stylesheets before processing the rest of the page. In PHP, I could use ob_flush()

.

I tried to do 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 part is res.render()

not sent. Is there a built-in way to send data with channels?

One way to do this is to manually load the EJS files and manually process them. I would also have to manually submit the appropriate headers. I prefer the inline method if it exists.

+3


source to share


1 answer


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 a "callback option" res.render()

that you can use to render the template without sending a response (if you don't, it res.render()

will throw an error). Alternatively, you can use app.render()

that does the same.

+3


source







All Articles