Return JavaScript script with Node.JS

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. However, the script is not embedded in the HTML page using the <script>

I'm using the Express framework. I tried to do it this way but it did not 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);
    }
});
    
asked by anonymous 03.09.2017 / 02:40

1 answer

1

You need to map the static files with this you can use in your 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;
    
03.09.2017 / 03:28