execute a javascript file when the user accesses a Node route

Asked

Viewed 126 times

0

I have the route / on my server.js:

app.get("/", function(req, res){
    res.sendFile("public/index.html", {root: __dirname})
})

And I need to run another javascript file that is in the same directory (or run the function that is contained in it) by accessing the route / before rendering the html.

2 answers

1


Just import the function of this file and call on its route. Example:

const minhaFuncao = require('./minhaFuncao.js');

app.get("/", function(req, res){
    minhaFuncao();
    res.sendFile("public/index.html", {root: __dirname})
})

Note: your file minhaFuncao.js must esar exporting its function

  • is there any exception p async functions? pq apparently my server.js n is running the function...

  • No. You should only use the async/await that will work

0

If you want to run this function in html, you can use express PUBLIC.

app.use("/", express.static(__dirname + "/sua-pasta"))


With it you can route a folder in the server directory, and in html, just vc put at the end of the url "./filename.js" to request.

In case, in html it would be

    <script scr='./nome-do-arquivo.js'></script>

then just put it right after the tag <body> to open before loading the page!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.