Search code examples
javascripthtmlnode.jsejsembedded-javascript

Use embedded js in ejs template to load static text file


I am currently working on a nodejs app using ejs view templates. I am trying to call upon large batches of text stored in a text file through embedded js in the template. Here is the code for the template currently

<!DOCTYPE html>
<html>
    <head>
        <link href="/assets/styles/index.css", rel="stylesheet", type="text/css">
    </head>
    <body>
        <% var name = 'A Tale of Two Star Crossed Idiots: Act ' + act%>
        <%include partial/header.ejs%>
        <p>
            //the following line is completely wrong
            <%= require('fs').readFileSync('.'+__dirname + '/assets/text/romeo and juliet/act' + act + '.txt') %>
        </p>
    </body>
</html>

This was the error that occured when i ran it

require is not defined
at eval (eval at compile (D:\Web Projects\NodeJs Test\node_modules\ejs\lib\ejs.js:618:12), <anonymous>:30:7)
at returnedFn (D:\Web Projects\NodeJs Test\node_modules\ejs\lib\ejs.js:653:17)
at tryHandleCache (D:\Web Projects\NodeJs Test\node_modules\ejs\lib\ejs.js:251:36)
at View.exports.renderFile [as engine] (D:\Web Projects\NodeJs Test\node_modules\ejs\lib\ejs.js:482:10)
at View.render (D:\Web Projects\NodeJs Test\node_modules\express\lib\view.js:135:8)
at tryRender (D:\Web Projects\NodeJs Test\node_modules\express\lib\application.js:640:10)
at Function.render (D:\Web Projects\NodeJs Test\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (D:\Web Projects\NodeJs Test\node_modules\express\lib\response.js:1008:7)
at D:\Web Projects\NodeJs Test\index.js:14:9
at Layer.handle [as handle_request] (D:\Web Projects\NodeJs Test\node_modules\express\lib\router\layer.js:95:5)

Does anyone know how to do this properly? Thanks.


Solution

  • Unfortunately requiring modules in ejs is not possible. You could alternatively try to load the file in the express part.

    //Node.JS Backend
    
    app.get("/foo",(req,res)=>{
      const act = req.query.act; //Act as Query Parameter in URL
      fs.readFile('.'+__dirname+'/assets/text/romeo and juliet/act'+act+'.txt',"utf8",(error,data)=>{
        //Add your error handling (if(error))
        res.render("file",{bar:data});
      });
    });

    <!DOCTYPE html>
    <html>
        <head>
            <link href="/assets/styles/index.css", rel="stylesheet", type="text/css">
        </head>
        <body>
            <% var name = 'A Tale of Two Star Crossed Idiots: Act ' + act%>
            <%include partial/header.ejs%>
            <p>
                //the following line is completely wrong
                <%- bar %>
            </p>
        </body>
    </html>

    Otherwise you could embed fs as script and load it when the document is finished, but this method should be more efficient i guess.