Search code examples
htmlnode.jsfileexpressswig-template

NodeJS : How to save a rendered view as a static .html file?


i'm using NodeJS for a school project and I have to generate a dynamic html page with Express and swig variables. But here comes the problem: I have to save the rendered view with the variables replaced by their content as a static .html file.

I tried to read the documentation about FS but I found nothing about taking a whole html page and put the html code inside a file. The only way I found was to "Right-click" and "save as" but that's not how I'm supposed to do it.

Any ideas or suggestions for how to do this?


Solution

  • If you are using swig templating engine then we need to get the output of the Swig template first:

    var swig  = require('swig');
    var template = swig.compileFile('/path/to/your/template.html');
    var output = template({
        foo: 'bar'
    });
    

    Now that you have the output, we can use fs to save the html:

    var fs = require('fs');
    fs.writeFile("/path/to/destination.html", output, function(err) {
        if(err) {
            return console.log(err);
        }
    
        console.log("The file was saved!");
    }); 
    

    Side note: Swig is NOT MAINTAINED anymore and has got security holes.