Search code examples
node.jsexpressssi

Node/Express server-side include equivalent for static files


Express has no equivalent to server-side includes for static client-side content.

Can someone recommend a good solution for robustly replicating this functionality (for web age headers and footers mostly), but without resorting to a full-scale HAML redesign? Partials is deprecated.


Solution

  • If you're using node.js, you should be able to just use require on the server file you want, assuming it's a js file:

    require('myfile.js');
    

    You will have to modify your js file to include a module export so you can gain access to various functions.

    myfile.js:

    module.exports = {
      nameToAccessFunction: myFunc,
      someOtherFunction: myOtherFunc
    }
    
    var someVarForMyFileStuff;
    function myFunc() { stuff... };
    function myOtherFunc() { other stuff... };
    

    Then your app file should look something like this when using that included file:

    var myFile = require('myfile.js');
    myFile.nameToAccessFunction();
    myFile.someOtherFunction();
    

    You can also nest your requires within other required files as much as you wish.