最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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
  • thats what you want? res.sendFile('/mods/example.js', {root: __dirname}); – Ami Hollander Commented Dec 31, 2016 at 18:08
  • Check the res.type method in the official docs. – noisypixy 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. – David Callanan Commented Dec 31, 2016 at 20:44
  • @noisypixy thanks got it to work! – David Callanan Commented Dec 31, 2016 at 21:32
Add a comment  | 

2 Answers 2

Reset to default 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

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.

发布评论

评论列表(0)

  1. 暂无评论