Reputation: 5958
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!
Upvotes: 4
Views: 19669
Reputation: 7299
The accepted answer is indeed accurate; however, it's worth noting that some individuals may arrive here with the intention of sending and executing JavaScript code within a web context. This can be accomplished by embedding a script tag along with the desired JavaScript code, as demonstrated below:
res.send(`
<script>
console.log('Hello world');
</script>
`);
By including this code in your response, you can effectively execute JavaScript on the client-side when the response is processed within a web browser.
Upvotes: 0
Reputation: 5958
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
Upvotes: 15