GN.
GN.

Reputation: 9839

Express: Stream an HTML file download from a string in request body

I have a string templateString that is being POSTed to a route in Express. How can this string be streamed as an HTML file and downloaded to the client?

res.setHeader('Content-type', 'text/html');
res.setHeader('Content-disposition', `attachment; filename=${testname}.html`);

^^ This will force the browser to download.

How to take the string in the request and pipe it to the client in the form of an HTML file?

Upvotes: 0

Views: 1444

Answers (2)

GN.
GN.

Reputation: 9839

Just figured it out.. This last simple line seems to work..

res.setHeader('Content-type', 'text/html');
res.setHeader('Content-disposition', `attachment; filename=${testname}.html`);
res.end(req.body.templateString);

Upvotes: 0

Aren Hovsepyan
Aren Hovsepyan

Reputation: 2047

I think you can make Buffer form the string and send it via res.end method.

let file = Buffer.from('Your string', 'utf8');

res.writeHead(200, {
    'Content-Type': 'text/html',
    'Content-disposition': `attachment; filename=${testname}.html`,
    'Content-Length': file.length
});

res.end(file);

You can read more about Buffer here

Upvotes: 1

Related Questions