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!
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!
Share Improve this question edited Jan 2 at 18:43 David Callanan asked Dec 31, 2016 at 18:05 David CallananDavid Callanan 5,96814 gold badges76 silver badges122 bronze badges 4 |2 Answers
Reset to default 15As 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
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.
res.type
method in the official docs. – noisypixy Commented Dec 31, 2016 at 18:10