dustjs icon indicating copy to clipboard operation
dustjs copied to clipboard

Dust js does not stream (show html) when using helmet

Open alon24 opened this issue 6 years ago • 0 comments

I want to use dust stream (or adaro stream) for async html template, so I tried using stream. What I found was that if I added helmet to my express app, then the html is not rendered and is shown as text insted of the html on screen. I tried dust.stream, and hoffman, and adaro, all the same result: https://stackoverflow.com/questions/56507447/dust-js-and-helmet-not-rendering-html Dust.stream:

var fs = require('fs'),
    path = require('path'),
    express = require('express'),
    request = require('request'),
    helmet = require('helmet'),
    dust = require('dustjs-linkedin');

dust.config.whitespace = true;
dust.config.cache = false;

// Define a custom `onLoad` function to tell Dust how to load templates
dust.onLoad = function(tmpl, cb) {
  fs.readFile(path.join('./views', path.relative('/', path.resolve('/', tmpl + '.dust'))),
              { encoding: 'utf8' }, cb);
};

var app = express();
app.use(helmet());

app.get('/streaming', function(req, res) {
  dust.stream('hello', {
    "async": request('http://www.dustjs.com/')
  }).pipe(res)
    .on('end', function() {
      console.log('Done streaming!');
    });
});

app.get('/rendering', function(req, res) {
  dust.render('hello', {
    "async": request('http://www.dustjs.com/')
  }, function(err, out) {
    res.send(out);
    console.log('Done rendering!');
  });
});


const port = process.env.PORT | 3002;
app.listen(port, function () {
  console.log(`Visit http://localhost:${port} to see streaming!`);
});

Hoffman:

hoffman = require('hoffman'),
    express = require('express'),
    helmet = require('helmet'),
    request = require('request');

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'dust');
app.engine('dust', hoffman.__express());

app.use(helmet());
// This is the important part-- it adds res.stream()
app.use(hoffman.stream);

app.get('/', function (req, res) {
  res.stream("hello", {
    "async": function(chunk, context, bodies, params) {
      return chunk.map(function(chunk) {
        // Introducting an artificial delay to make streaming more apparent
        setTimeout(function() {
          request('http://www.dustjs.com/')
          .on('data', chunk.write.bind(chunk))
          .on('end', chunk.end.bind(chunk));
        }, 3000);
      });
    }
  });
});
const port = process.env.PORT | 3007;

app.listen(port, function () {
  console.log(`Visit http://localhost:${port} to see streaming!`);
});

image

Can you help me find a solution

alon24 avatar Jun 08 '19 17:06 alon24