4

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!

4
  • thats what you want? res.sendFile('/mods/example.js', {root: __dirname}); Commented Dec 31, 2016 at 18:08
  • Check the res.type method in the official docs. Commented Dec 31, 2016 at 18:10
  • @AmiHollander the reason i amen't using the res.sendFile function is because I have to change the content of the file using code such as adding text to the beginning of the file. Commented Dec 31, 2016 at 20:44
  • @noisypixy thanks got it to work! Commented Dec 31, 2016 at 21:32

2 Answers 2

15

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

Sign up to request clarification or add additional context in comments.

3 Comments

Hi David, I'd also recommend using var something = fs.createReadStream('./mods/example.js') and something.pipe(res) to optimise it.
This still just displays the js as a string in the browser - it does not execute.
@ydennis The idea is to let the browser know that the file type is JavaScript. It is up to the browser what it wants to do with that file type. If you want it to execute you can create a HTML file and enter the script in there.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.