Tuesday 16 May 2017

How to res.sendFile the Swig output?

I currently have a Angular2 huge app hosted on node. I want to make a couple of smaller pages (widgets) that are not part of my Angular2 app but still hosted on the same node server. I need to use Swig to interpolate some variables into the html. Here is the code I currently have:

import express from 'express';
import path from 'path';
import swig from 'swig';
const router = express.Router();
const rootPath = path.join(__dirname, '../../../');

let assetsPath = path.join(rootPath, './server/app/widgets/assets');
let projectedGrowthWidgetPath = path.join(rootPath, './server/app/widgets/assets/projected-growth-widget/projected-growth-widget.template.html');

router.get('/projected-growth-widget', (req, res, next) => {
    var template = swig.compileFile(projectedGrowthWidgetPath);
    var output = template({
        base: '/web-AOT/' 
    });
    res.sendFile(output);
    console.log('OUTPUT', output) // currently has the correct HTML after interpolated with Swig
});

router.use('/assets', (req, res, next) => {
    res.sendFile(path.join(assetsPath, req.path));
});

router.use((req, res, next) => {
    res.status(404).end();
});

module.exports = router;

How can I simply send the output as an html file? It is not working right now.

I realize I could use something like this:

app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'html');
app.engine('html', swig.renderFile);

But I currently do not have access to app in this file and I do not want to reset any of the settings on app because I do not want to break anything else on the node server (as our api is hosted here as well). What is the best way for me to simply send the interpolated html file back to the client?



via georgej

No comments:

Post a Comment