Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Express how do I send response as javascript or other file type

I have code that reads the file example.js and sends it to the client.

app.get('/mods/example.js', (req, res) => {
    fs.readFile('./mods/example.js',
        { encoding: 'utf-8' },
        (err, data) => {
            if (!err) {
                res.send("var example = new Mod();" + data);
            }
        },
    );
});

The problem is how do I send the response as a JavaScript file?

When I open the file in the web browser, it is a HTML file, not a JS file.

Thanks in advance!

like image 660
David Callanan Avatar asked Oct 29 '25 17:10

David Callanan


1 Answers

As suggested by noisypixy, I used the res.type function to change the type of the response to javascript.

res.type('.js');
res.send("var john = new Human();");

There are a lot of other file types such as html, json, png.

API reference with example code: http://expressjs.com/en/4x/api.html#res.type

like image 136
David Callanan Avatar answered Oct 31 '25 07:10

David Callanan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!