0

I have a javascript file with more than 200 lines of code for front end logic like what happens when someone clicks on button, image, etc. like a game.

I am not able to figure this out. How to link/ include, tell expressjs to use that file for front end logic and not just rely on .ejs files ?

I am not asking for module.exports to export particular parts from file. I want the whole file to be exported.

Please help.

1
  • 1
    app.use("/", express.static(__dirname)); it will serve your static files so you can use <script tag to include the file. Commented Apr 29, 2018 at 10:29

2 Answers 2

1

First you should tell express where your static file is located:

app.use(express.static(path.join(__dirname, 'yourFolder')));

Then in your route where you are rendering view you can do something like this:

return res.render("yourView",{
       param1: param1,
       scripts: [
           'javascripts/yourFile.js'
        ]
});

'scripts' array is not accessible inside ejs file. In footer.ejs you can do:

<% if ( typeof scripts !== 'undefined') { %>
    <% scripts.forEach(function(script){ %>
        <script src="/<%- script %>"></script>
    <% }); %>
<% } %>
Sign up to request clarification or add additional context in comments.

Comments

0

You could also change your <script> lines in your file to point towards a path like follows:

<script src="/filejs"></script>

Then in your app.js add another endpoint called /filejs with the following code:

app.get('/filejs', function(req, res) {
res.sendFile(__dirname + '/folder/file.js') //change this to your file path
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.