简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM