0

Im trying to create a file from a string that contains html content for example:

const html = "<!DOCTYPE html> <html> <body> <p>example</p> </body> </html>";

Now how would you create a read stream and pipe it to the response without creating the file locally?

  • I don't understand why not creating the HTML locally, but anyway maybe this NPM package will be what you need: https://www.npmjs.com/package/create-html – fedeteka Jul 21 '20 at 23:05

1 Answers1

0

If you are using express you can do the following

// as string (for short strings)
router.get('/my-html', function (req, res) {
  const html = "<!DOCTYPE html> <html> <body> <p>example</p> </body> </html>";
  
  res.type('html');
  res.send(html);
})

Or

// as stream (for large strings)
router.get('/my-html', function (req, res) {
  const html = "<!DOCTYPE html> <html> <body> <p>example</p> </body> </html>";
  const readStream = Readable.from(html)
  
  res.type('html');
  readStream.pipe(res);
})
Daniel
  • 2,288
  • 1
  • 14
  • 22