Return Javascript script with Node.JS

Asked

Viewed 445 times

1

Using Node.JS I want to read a Javascript script in a folder and return it.
It turns out that when I access the file through the browser, the code appears normally.
But the script is not embedded in the HTML page using the tag <script>

I’m using the Express framework. I tried to do this way but it didn’t work.

app.get(/\/.+/, function(req, res){
    var file = __dirname + "/www/public" + req.path;

    if(fs.existsSync(file)){
        if(file.match(/\.js$/)){
            res.header("Content-Type", "application/javascript");
        }

        res.sendFile(file);
        res.status(200);
    } else {
        res.sendFile(__dirname + "/www/404.html");
        res.status(404);
    }
});

1 answer

1


need to map the static files with this you will be able to use in their pages the files (css,js,etc..)

var express = require('express');
var app = express();


//Middlewares
app.use(express.static('./app/public')); // mapeando arquivos estaticos com express

app.use(express.static('./node_modules'))

module.exports = app;
  • This worked, but Javascript is still not embedded in the HTML page. I open it in the direct link, but on the page is as if the tag <script> even existed. No error appears. Detail which CSS file is working correctly, the problem is only with . js

  • ta using ejs or Pug ?

  • Since I don’t know what this is about, I guess neither of you.

  • 1

    My God, I’m sorry to waste your time... I use Noscript, and I didn’t enable localhost to run code. ' Thank you for showing me this more practical way of giving access to files from a folder.

Browser other questions tagged

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